class Digit { public Digit(double d) { val = d; } public double val; // 用户定义的从数字到双精度的转换 public static implicit operator double(Digit d) { Console.WriteLine("Digit to double implict conversion called"); return d.val; } // 用户定义的从双精度到数字的转换 public static implicit operator Digit(double d) { Console.WriteLine("double to Digit implict conversion called"); return new Digit(d); } } class Program { static void Main(string[] args) { Digit dig = new Digit(7); //This call invokes the implicit "double" operator double num = dig; //This call invokes the implicit "Digit" operator Digit dig2 = 12; Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val); Console.ReadLine(); } }
输出:
从数字到双精度
隐式转换称为
num = 7 dig2 = 12
.NET Fiddle上的实时演示