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

后端 未结 7 1789
悲哀的现实
悲哀的现实 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:05

    Here is a solution that worked for myself :

    public class MyTestClass
    {
       private int a;
       private string str;
    
       public MyTestClass()
       {
          a = 0;
          str = null;
       }
    
       public MyTestClass(int a, string str)
       {
          this.a = a;
          this.str = str;
       }
    
       public MyTestClass Clone
       {
          get
          {
             return new MyTestClass(this.a, this.str);
          }
       }
    }
    

    Somewhere else in the code :

    MyTestClass test1 = new MyTestClass(5, "Cat");
    MyTestClass test2 = test1.Clone;
    

提交回复
热议问题