Requirements for operator overloading:
The reload instance is:
The classes to be overloaded are defined as follows:
1 class LimitedInt 2 { 3 const int MaxValue = 100; 4 const int MinValue = 0; 5 6 public static LimitedInt operator -(LimitedInt x) 7 { 8 LimitedInt li = new LimitedInt(); 9 li.TheValue = -x.TheValue;10 return li;11 }12 public static LimitedInt operator -(LimitedInt x,double y)13 {14 LimitedInt li = new LimitedInt();15 li.TheValue = x.TheValue - (int)y;16 return li;17 }18 19 private int _TheValue = 0;20 public int TheValue21 {22 get 23 {24 return _TheValue;25 }26 set27 {28 _TheValue = value;29 }30 }31 }
It can be seen that the first overload operator is a single object operator, with a-sign
The second operator is A-number, but a binary operator.
In this case, you can make the following calls:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 LimitedInt x = new LimitedInt(); 6 x.TheValue = 13; 7 8 double y = 7; 9 10 LimitedInt li = new LimitedInt();11 12 li =x-y;13 14 Console.WriteLine("{0}",li.TheValue);15 16 li = -x;17 18 Console.WriteLine("{0}",li.TheValue);19 20 Console.ReadKey();21 }22 }
The output is 6 and-13. The operation is correct.
C # Operator Overloading