为什么不能在静态类中重载运算符?
我有一个 System.Net.IPAddress 的扩展类,我想重载二元运算符 >、<、==
但编译器告诉我不能重载内部的这些运算符一个静态类,我的其他扩展方法必须有它。这有什么特别的原因吗?
谢谢。
I have an extension class for System.Net.IPAddress and I was wanting to overload the binary operators >, <, ==
but the compiler is telling me that I can't overload those operators inside a static class, which I must have for my other extension methods. Is there a particular reason for this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
运算符必须与声明它们的类型的实例相关。由于不能拥有静态类的实例,因此定义运算符是没有意义的。
.NET 中没有“扩展运算符”。
出于您的目的,请考虑实现
IComparer
(涵盖<
和>
)和/或IEqualityComparer
(涵盖==
,或者您可能只使用返回0
的比较;这取决于您是否考虑“排序相等”和“等于”相同)。Operators must relate to instances of the type in which they are declared. Since you can't have instances of a static class, it makes no sense to define operators.
There are no "extension operators" in .NET.
For your purposes, consider implementing an
IComparer<T>
(covers<
and>
) and / orIEqualityComparer<T>
(covers==
, or you might just use compare returning0
; it depends whether you consider "sorts equal" and "equal" as the same).