在 C# 中重载复合赋值运算符的简单方法?
有没有人有一个关于如何在 C# 中重载复合赋值运算符的非常简单的示例?
Does anyone have a very simple example of how to overload the compound assignment operator in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能显式重载复合赋值运算符。但是,您可以重载主运算符,编译器会扩展它。
x += 1
纯粹是x = x + 1
的语法糖,后者就是它将被翻译成的内容。如果重载+
运算符,它将被调用。MSDN 运算符重载教程
You can't explicitly overload the compound assignment operators. You can however overload the main operator and the compiler expands it.
x += 1
is purely syntactic sugar forx = x + 1
and the latter is what it will be translated to. If you overload the+
operator it will be called.MSDN Operator Overloading Tutorial
根据 C# 规范,+= 不在可重载运算符列表中。我认为,这是因为它也是一个赋值运算符,不允许重载。但是,与此处其他答案中所述不同,“x += 1”与“x = x + 1”不相同。 C# 规范“7.17.2 复合赋值”非常清楚:
重要的部分是最后一部分:x 仅计算一次。因此,在这样的情况下:
如何表述你的陈述可以(并且确实)产生影响。但我认为,在大多数情况下,差异可以忽略不计。 (即使我刚刚遇到过一个,但事实并非如此。)
因此,问题的答案是:不能覆盖 += 运算符。对于可以通过简单的二元运算符实现意图的情况,可以覆盖 + 运算符并实现类似的目标。
According to the C# specification, += is not in the list of overloadable operators. I assume, this is because it is an assignment operator as well, which are not allowed to get overloaded. However, unlike stated in other answers here, 'x += 1' is not the same as 'x = x + 1'. The C# specification, "7.17.2 Compound assignment" is very clear about that:
The important part is the last part: x is evaluated only once. So in situations like this:
it can (and does) make a difference, how to formulate your statement. But I assume, in most situations, the difference will negligible. (Even if I just came across one, where it is not.)
The answer to the question therefore is: one cannot override the += operator. For situations, where the intention is realizable via simple binary operators, one can override the + operator and archieve a similiar goal.
您无法在 C# 中重载这些运算符。
You can't overload those operators in C#.