Why must I define a commutative operator twice?

前端 未结 4 1971
[愿得一人]
[愿得一人] 2021-01-04 11:26

I wonder if I must define a commutative operator (like *) twice!

public static MyClass operator *(int i, MyClass m)
{
    return new MyClass(i *         


        
4条回答
  •  -上瘾入骨i
    2021-01-04 12:01

    Order is sometimes important in operators, the classic examples being subraction (-) and division (/). However, it can also apply to multiplication:

    Consider, for example, that they are vectors - x is a (2×1) vector, and y is a (1×2) vector. If we interpret * as matrix multiplication, then x * y is a (2×2) vector, but y * x is a (1×1) vector.

    As such, the C# compiler does not assume that binary operators are commutative, even if they commonly are (addition (+), multiplication (*), etc).

提交回复
热议问题