Why does C# require operator overloads to be static methods rather than member functions (like C++)? (Perhaps more specifically: what was the design motivation for this decision?)
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Take a look at this post.
A couple of reasons, the primary seeming to be to preserve operator symmetry (such that the left hand side of a binary operation does not get special treatment, as being responsible for dispatching the operation).
回答2:
Answered in excruciating detail here:
http://blogs.msdn.com/ericlippert/archive/2007/05/14/why-are-overloaded-operators-always-static-in-c.aspx
There is also another subtler point about value types and instance operators. Static operators make this kind of code possible:
class Blah {
int m_iVal;
public static Blah operator+ (Blah l, int intVal)
{
if(l == null)
l = new Blah();
l.m_iVal += intVal;
return l;
}
}
//main
Blah b = null;
b = b + 5;
So you can invoke the operator, even though the reference is null. This wouldn't be the case for instance operators.
回答3:
Perhaps its best to think why should the methods not be static. There is no need for state and hence this.