为什么 C# 运算符重载必须是静态的?
为什么 C# 要求运算符重载是静态方法而不是成员函数(如 C++)? (或许更具体地说:这个决定的设计动机是什么?)
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?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Eric Lippert 在 博客文章现已被删除。这是 存档版本。
关于值类型和实例运算符还有另一个更微妙的点。静态运算符使这种代码成为可能:
因此即使引用为空,您也可以调用该运算符。对于实例操作员来说,情况并非如此。
This has been answered in excruciating detail by Eric Lippert in a blog post that has since been removed. Here is the archived version.
There is also another subtler point about value types and instance operators. Static operators make this kind of code possible:
So you can invoke the operator, even though the reference is null. This wouldn't be the case for instance operators.
看一下 这篇文章。
有几个原因,最主要的似乎是保持运算符对称性(这样二元运算的左侧不会得到特殊处理,因为负责分派操作)。
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).
也许最好想想为什么这些方法不应该是静态的。不需要国家,因此也是如此。
Perhaps its best to think why should the methods not be static. There is no need for state and hence this.