1 class Complex 2 { 3 //保存转换的值 4 Int32 v; 5 6 public Complex(Int32 x) 7 { 8 v = x; 9 } 10 11 public Int32 ToInt32() 12 { 13 return v; 14 } 15 16 /// <summary> 17 /// 显示转换 重载 18 /// </summary> 19 /// <param name="c"></param> 20 /// <returns></returns> 21 public static explicit operator Int32(Complex c) 22 { 23 return c.ToInt32(); 24 } 25 26 /// <summary> 27 /// 隐式转换 重载 28 /// </summary> 29 /// <param name="x"></param> 30 /// <returns></returns> 31 public static implicit operator Complex(Int32 x) 32 { 33 return new Complex(x); 34 } 35 }
1 static void Main(string[] args) 2 { 3 Complex c = 10;//隐式转换 implicit 4 Int32 num = (Int32)c;//显示转换 explicit 5 6 Console.WriteLine(num); 7 8 Console.Read(); 9 }