implicit
Implicit关键字用于声明隐式的用户定义类型转换运算符。它可以实现2个不同类的隐式转换 ,提高代码的可读性。但是需要注意使用隐式转换操作符之后,在编译时会跳过异常检查,所以隐式转换运算符应当从不引发异常并且从不丢失信息,否则在运行时会出现一些意想不到的问题。
class Digit { public Digit(double d) { val = d; } public double val; // User-defined conversion from Digit to double public static implicit operator double(Digit d) { return d.val; } // User-defined conversion from double to Digit public static implicit operator Digit(double d) { 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(); } }
Explicit
Explicit关键字声明必须通过转换来调用的用户定义的类型转换运算符。不同于隐式转换,显式转换运算符必须通过转换的方式来调用,如果缺少了显式的转换,在编译时就会产生错误。
class Digit { public Digit(double d) { val = d; } public double val; // User-defined conversion from Digit to double public static explicit operator double(Digit d) { return d.val; } // User-defined conversion from double to Digit public static explicit operator Digit(double d) { 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 = (double)dig; //This call invokes the implicit "Digit" operator Digit dig2 = (Digit)12; Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val); Console.ReadLine(); } }