首页 > 代码库 > C#运算符重载

C#运算符重载

运算符重载要求:

 

重载的实例为:

要定义重载的类中定义如下:

 1 class LimitedInt 2     { 3         const int MaxValue = http://www.mamicode.com/100; 4         const int MinValue = http://www.mamicode.com/0; 5  6         public static LimitedInt operator -(LimitedInt x) 7         { 8             LimitedInt li = new LimitedInt(); 9             li.TheValue = http://www.mamicode.com/-x.TheValue;10             return li;11         }12         public static LimitedInt operator -(LimitedInt x,double y)13         {14             LimitedInt li = new LimitedInt();15             li.TheValue = http://www.mamicode.com/x.TheValue - (int)y;16             return li;17         }18 19         private int _TheValue = http://www.mamicode.com/0;20         public int TheValue21         {22             get 23             {24                 return _TheValue;25             }26             set27             {28                 _TheValue =http://www.mamicode.com/ value;29             }30         }31 }

可见,第一个重载的运算符是单目运算符,-号

第二个还是 -号,但是是双目运算符。

此时可以做如下调用:

 1 class Program 2     { 3         static void Main(string[] args) 4         { 5             LimitedInt x = new LimitedInt(); 6             x.TheValue = http://www.mamicode.com/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     }

输出为6和-13,可见操作正确。

C#运算符重载