標籤:c# .net implicit explicit
在類型轉換時常會遇到隱式轉換和顯式轉換。那我們自訂的類型要如何去定義隱式轉換和顯式轉換?我們來看一段代碼
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
C#之自訂的implicit和explicit轉換