在C#中我们可以使用 operator 关键字来重载运算符,首先先来看看哪些运算符能够被重载
Operators |
Overloadability |
---|---|
These unary operators can be overloaded. |
|
These binary operators can be overloaded. |
|
The comparison operators can be overloaded (but see the note that follows this table). |
|
The conditional logical operators cannot be overloaded, but they are evaluated using & and |, which can be overloaded. |
|
The array indexing operator cannot be overloaded, but you can define indexers. |
|
The cast operator cannot be overloaded, but you can define new conversion operators (seeexplicit and implicit). |
|
Assignment operators cannot be overloaded, but +=, for example, is evaluated using +, which can be overloaded. |
|
=, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is,new, sizeof, typeof |
These operators cannot be overloaded. |
那么要怎么使用 operator 关键字呢?看看下面的代码就能很快明白了
class Program { static void Main(string[] args) { Test t1 = new Test() { count=1, value=10 }; Test t2 = new Test() { count=1, value=10 }; Test tr = t1 + t2; Console.WriteLine(tr.ToString());//count:2 value:20 Console.WriteLine("按任意键结束"); Console.Read(); } } public class Test { public int value; public int count; public static Test operator +(Test test1, Test test2) { Test testresult = new Test(); testresult.count = test1.count + test2.count; testresult.value = test1.value + test2.value; return testresult; } public override string ToString() { return string.Format("count:{0} value:{1}", this.count, this.value); } }
这里我定义了一个 名叫Test的类,并且重写了他相加的运算符.这样我想让两个Test类型相加时就可以使用自定义的相加逻辑了.
当然,其他的运算符重写也是同样道理.
这里要说一下,判断用的运算符需要成对重写,比如 == 和 !=