在 C# 中重载复合赋值运算符的简单方法?

发布于 2024-09-02 16:54:31 字数 42 浏览 3 评论 0原文

有没有人有一个关于如何在 C# 中重载复合赋值运算符的非常简单的示例?

Does anyone have a very simple example of how to overload the compound assignment operator in C#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

红衣飘飘貌似仙 2024-09-09 16:54:31

您不能显式重载复合赋值运算符。但是,您可以重载主运算符,编译器会扩展它。

x += 1 纯粹是 x = x + 1 的语法糖,后者就是它将被翻译成的内容。如果重载 + 运算符,它将被调用。

MSDN 运算符重载教程

public static Complex operator +(Complex c1, Complex c2) 
{
   return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}

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 for x = 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

public static Complex operator +(Complex c1, Complex c2) 
{
   return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
舟遥客 2024-09-09 16:54:31

根据 C# 规范,+= 不在可重载运算符列表中。我认为,这是因为它也是一个赋值运算符,不允许重载。但是,与此处其他答案中所述不同,“x += 1”与“x = x + 1”相同。 C# 规范“7.17.2 复合赋值”非常清楚:

... the operation is evaluated as x = x op y, except that x is evaluated only once

重要的部分是最后一部分:x 仅计算一次。因此,在这样的情况下:

A[B()] = A[B()] + 1; 

如何表述你的陈述可以(并且确实)产生影响。但我认为,在大多数情况下,差异可以忽略不计。 (即使我刚刚遇到过一个,但事实并非如此。)

因此,问题的答案是:不能覆盖 += 运算符。对于可以通过简单的二元运算符实现意图的情况,可以覆盖 + 运算符并实现类似的目标。

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 operation is evaluated as x = x op y, except that x is evaluated only once

The important part is the last part: x is evaluated only once. So in situations like this:

A[B()] = A[B()] + 1; 

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.

自我难过 2024-09-09 16:54:31

您无法在 C# 中重载这些运算符。

You can't overload those operators in C#.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文