Is there a workaround for overloading the assignment operator in C#?

后端 未结 7 1788
悲哀的现实
悲哀的现实 2020-12-13 02:43

Unlike C++, in C# you can\'t overload the assignment operator.

I\'m doing a custom Number class for arithmetic operations with very large numbers and I want it to h

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 03:17

    You won't be able to work around it having the C++ look, since a = b; has other semantics in C++ than in C#. In C#, a = b; makes a point to the same object like b. In C++, a = b changes the content of a. Both has their ups and downs. It's like you do

    MyType * a = new MyType();
    MyType * b = new MyType(); 
    a = b; /* only exchange pointers. will not change any content */
    

    In C++ (it will lose the reference to the first object, and create a memory leak. But let's ignore that here). You cannot overload the assign operator in C++ for that either.

    The workaround is easy:

    MyType a = new MyType();
    MyType b = new MyType();
    
    // instead of a = b
    a.Assign(b);
    

    Disclaimer: I'm not a C# developer

    You could create a write-only-property like this. then do a.Self = b; above.

    public MyType Self {
        set {
            /* copy content of value to this */
            this.Assign(value);
        }
    }
    

    Now, this is not good. Since it violates the principle-of-least-surprise (POLS). One wouldn't expect a to change if one does a.Self = b;

提交回复
热议问题