使用复合赋值运算符时,操作数是如何排序的?
How are the operands ordered when using a compound assignment operator?
使用 C# 时,复合赋值运算符(+=
、*=
等)是从相应的二元运算符自动创建的:
Compound assignment operators cannot be explicitly overloaded. However, when you overload a binary operator, the corresponding compound assignment operator, if any, is also implicitly overloaded. For
example, += is evaluated using +, which can be overloaded. - C# Language Reference
如果二元运算符是非交换的,例如矩阵乘法,那么操作数的顺序很重要,例如A * B != B * A
。因此,如果在这种情况下使用复合赋值运算符,了解它们处理操作数的顺序很重要。
自动创建的复合赋值运算符以什么顺序放置操作数,例如x *= y
等同于 x = x * y
还是 x = y * x
?
根据Assignment operators (C# reference)
对于二元运算符 op,
形式的复合赋值表达式
x op= y
相当于
x = x op y
除了 x 只计算一次。
使用 C# 时,复合赋值运算符(+=
、*=
等)是从相应的二元运算符自动创建的:
Compound assignment operators cannot be explicitly overloaded. However, when you overload a binary operator, the corresponding compound assignment operator, if any, is also implicitly overloaded. For example, += is evaluated using +, which can be overloaded. - C# Language Reference
如果二元运算符是非交换的,例如矩阵乘法,那么操作数的顺序很重要,例如A * B != B * A
。因此,如果在这种情况下使用复合赋值运算符,了解它们处理操作数的顺序很重要。
自动创建的复合赋值运算符以什么顺序放置操作数,例如x *= y
等同于 x = x * y
还是 x = y * x
?
根据Assignment operators (C# reference) 对于二元运算符 op,
形式的复合赋值表达式x op= y
相当于
x = x op y
除了 x 只计算一次。