<textarea cols="50" rows="15" name="code" class="c-sharp">class Number { private int val; public Number(int val) { this.val = val; } public static Number operator +(Number lhs, Number rhs) { return new Number(lhs.val + rhs.val); } public static Number operator++(Number lhs){ return new Number(++lhs.val); } public override string ToString() { return ""+val; } }</textarea>
要求如果重载了==,必须也重载!=,同样<和>,<=和>=必须一起重载。
重载==,建议大家也一起重写equals方法,并使用==方法。同时提供getHashcode方法
下面一个综合的例子,包括了类型转换符
<textarea cols="50" rows="15" name="code" class="c-sharp">class Program { static void Main(string[] args) { Number num = new Number(2); int a = (int)num; Number num1 = 2; Number result = 3+num; //运算时,如果能进行隐式转换,自动进行了转换 } } class Number { private int val; public Number(int val) { this.val = val; } public static Number operator +(Number lhs, Number rhs) { return new Number(lhs.val + rhs.val); } public static Number operator++(Number lhs){ return new Number(++lhs.val); } public static implicit operator Number(int val) { return new Number(val); } public static explicit operator int(Number num) { return num.val; } public override string ToString() { return ""+val; } }</textarea>