在类型转换时常会遇到隐式转换和显式转换。那我们自定义的类型要如何去定义隐式转换和显式转换?我们来看一段代码
public class Rational { private Int32 _inner_int = 0; public Rational() { } public Rational(Int32 num) { this._inner_int = num; } public Int32 ToInt32() { return this._inner_int; } // Implicitly constructs and returns a Rational from an Int32 public static implicit operator Rational(Int32 num) { return new Rational(num); } // Explicitly returns an Int32 from a Rational public static explicit operator Int32(Rational r) { return r.ToInt32(); } public override string ToString() { //return base.ToString(); String s = String.Format("{0}", this._inner_int); return s; } }
class Program { static void Main(string[] args) { Rational r1 = 10; Console.WriteLine(r1); Int32 i = r1; Console.WriteLine(i); Console.ReadLine(); } }这时编辑会报错,见下图
从提示可以看到,是因为Int32 i=r1时缺少了显式转换。现在我们添加显示转换,修改后的代码及输出结果如下:
结果正常输出为10.
那为什么会这样呢?究其原因是在Rational转换成 Int32时,指定了explicit(显式的),所以必须要指定转换类型Int32。如果将explicit换成implicit(隐式),原来的代码将可以正常运行。
修改后的Rational
public class Rational { private Int32 _inner_int = 0; public Rational() { } public Rational(Int32 num) { this._inner_int = num; } public Int32 ToInt32() { return this._inner_int; } // Implicitly constructs and returns a Rational from an Int32 public static implicit operator Rational(Int32 num) { return new Rational(num); } // Explicitly returns an Int32 from a Rational public static <span style="color:#ff0000;">implicit</span> operator Int32(Rational r) { return r.ToInt32(); } public override string ToString() { //return base.ToString(); String s = String.Format("{0}", this._inner_int); return s; } }测试代码及输出结果
可见explicit和implicit影响着类型的显式转换和隐式转换。
其实在Rational r1=10已经执行了隐式转换,对应的转换代码如下:
// Implicitly constructs and returns a Rational from an Int32 public static implicit operator Rational(Int32 num) { return new Rational(num); }如果将implicit换成explicit,Rational r1=10也将会报错(可以自行测试)。
转载请注明出处:http://blog.csdn.net/xxdddail/article/details/38057563
原文地址:http://blog.csdn.net/xxdddail/article/details/38057563