1、操作符重载
a、构造器转换——将一个类型值显示或隐式赋给另一个类型
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
将Nullable类型转换为ValueTypepublic static explicit operator T(T? value) { return value.Value; }
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
将ValueType类型转换为Nullablepublic static implicit operator T?(T value) { return new T?(value); }
b、操作符重载
函数将被编译器翻译为特定名称函数,必须为static、public
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
操作符重载示例public static int operator +(Truck t1, Truck t2) { return t1.capacity + t2.capacity; } public static Truck operator ++ (Truck t) { t.Capacity++; return t; } public static bool operator ==(Truck t1, Truck t2) { if (t1.Capacity == t2.Capacity) return true; return false; } public static bool operator !=(Truck t1, Truck t2) { if (t1.Capacity == t2.Capacity) return false; return true; } //负号 public static Truck operator -(Truck t) { return new Truck(-t.Capacity); } //减号 public static Truck operator -(Truck t1, Truck t2) { return new Truck(t1.Capacity-t2.Capacity); }
2、Nullable值的操作
Nullable类型是继承于ValueType的类型,内含两个字段,一个是hasValue,一个是value
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
Nullable值的使用int? a = 5; double? b = null ; Console.WriteLine("a={0}, b={1}", a, b);
空接合符 ??
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
空接合符int? a = null; int? b = 5; Console.WriteLine(a??10); Console.WriteLine(b ?? 100);
上例输出:
3、泛型委托
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
泛型委托示例public delegate T Callback<T>(T t) where T : Truck; static void Main() { Callback<Truck> c = null; c += delegate(Truck t) { Console.WriteLine(t); return t; }; c(new Truck(100)); }