.NET 中的运算符重载
在什么情况下您会考虑重载 .NET 中的运算符?
In what situations would you consider overloading an operator in .NET?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
在什么情况下您会考虑重载 .NET 中的运算符?
In what situations would you consider overloading an operator in .NET?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(5)
Equals
的任何地方重载 == 和 !=IComparable
的任何地方考虑(不太强烈)重载比较运算符Nullable
)提供显式转换黄金法则是如果含义不完全明显,不重载运算符。例如,我认为在
Stream
上有一个 + 运算符会很奇怪 - 它可能意味着“在这里创建一个可写的 T,以便写入结果写入两者”或者它可能意味着“一篇接着一篇地读”或者可能是其他的东西。根据我的经验,除了 == 和 != 之外,很少会重载任何内容。
Equals
IComparable<T>
Nullable<T>
)The golden rule is not to overload operators if the meaning isn't entirely obvious. For example, I think it would be pretty odd to have a + operator on
Stream
- it could mean "make a writable T here, so that writes to the result write to both" or it could mean "read one after the other" or probably other things.In my experience it's pretty rare to overload anything other than == and !=.
我认为框架设计指南提供了一些不错的建议:
I think the Framework design guidelines provide some decent advice:
我考虑在这种情况下重写运算符:
I consider overriding operators i this cases:
我确实请求关闭它,但也许它可以保持打开状态(我试图改变主意,但显然你不能撤销关闭请求:P)
我个人会回答:从不。
我从来不认为实现运算符重载是一个好主意。只有一个例外:如果我正在编写某种集合(这种情况并不经常发生)并且我想实现索引器
[]
。在我个人看来,我认为重写
==
和其他类似的东西是不合适的。但话又说回来,我并不在复杂的数学和金融领域工作,这些东西可能在这些领域有用。但我不能根据这件事的经验来说话(实际上,我可以在金融界,但我们在那里没有这样做)。I did request to close this, but perhaps it can remain open (I tried to change my mind but apparently you can't revoke a close request :P)
I will answer personally: never.
I never think it's a good idea to implement operator overloading. There is only one exception: If I'm writing some sort of collection (it doesn't happen very often) and I want to implement the indexers
[]
.In my personal opinion, I do not think it is ever appropriate to be overriding
==
, and other such things. But then again, I do not work in complex fields of maths and finance, where such things may be useful. But I can't speak from experience in that matter (actually, I can in the finance world, and we didn't do it there).我会考虑使用运算符重载对表示逻辑值的类型进行算术运算。例如,有时我希望
Point
具有+
和-
运算符的重载。I would consider using operator overloading for arithmetic operations on types that represent a logical value. For instance, there have been occasions when I wished that
Point
had an overload for the+
and-
operators.