Why must I define a commutative operator twice?

前端 未结 4 2002
[愿得一人]
[愿得一人] 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条回答
  •  醉话见心
    2021-01-04 12:03

    You don't have to do that - you only need to do that if you want to be able to write:

    MyClass x = ...;
    
    MyClass y = x * 5;
    MyClass z = 5 * x;
    

    If you only want one of the bottom two lines to be valid, you can delete the other operator overload.

    Basically, the C# language doesn't assume that multiplication is commutative even in terms of the types involved.

提交回复
热议问题