在类型转换时常会遇到隐式转换和显式转换。那我们自己定义的类型要怎样去定义隐式转换和显式转换?我们来看一段代码
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
时间: 2024-11-04 22:13:35