问题
I wanted to overload an operator in a class , and have it private so that it could only be used from within the class.
However, when I tried to compile I got the error message "User-defined operator ... must be declared static and public:
Why do they have to be public?
回答1:
To answer half part of your question you may see the blog post by Eric Lippert.
Why are overloaded operators always static in C#?
Rather, the question we should be asking ourselves when faced with a potential language feature is "does the compelling benefit of the feature justify all the costs?" And costs are considerably more than just the mundane dollar costs of designing, developing, testing, documenting and maintaining a feature. There are more subtle costs, like, will this feature make it more difficult to change the type inferencing algorithm in the future? Does this lead us into a world where we will be unable to make changes without introducing backwards compatibility breaks? And so on.
In this specific case, the compelling benefit is small. If you want to have a virtual dispatched overloaded operator in C# you can build one out of static parts very easily. For example:
public class B {
public static B operator+(B b1, B b2) { return b1.Add(b2); }
protected virtual B Add(B b2) { // ...
And there you have it. So, the benefits are small. But the costs are large. C++-style instance operators are weird. For example, they break symmetry. If you define an operator+ that takes a C and an int, then c+2 is legal but 2+c is not, and that badly breaks our intuition about how the addition operator should behave.
For your question's other part: Why they should be public.
I was not able to find any authentic source, but IMO, if they are not going to be public, and may be used inside a class only, then this can be done using a simple private method, rather than an overloaded operator.
You may see the blog post by RB Whitaker
Operator Overloading
All operator overloads must be public and static, which should make sense, since we want to have access to the operator throughout the program, and since it belongs to the class as a whole, rather than any specific instance of the class.
来源:https://stackoverflow.com/questions/13150320/why-must-overloaded-operators-be-declared-public