implicit 關鍵字用於聲明隱式的用戶定義類型轉換運算符。如果可以確保轉換過程不會造成數據丟失,則可使用該關鍵字在用戶定義類型和其他類型之間進行隱式轉換。隱式轉換可以通過消除不必要的類型轉換來提高源代碼的可讀性。 但是,因為隱式轉換不需要程序員將一種類型顯式強制轉換為另一種類型,所以使用隱式轉換時必須格外小心,以免出現意外結果。 一般情況下,隱式轉換運算符應當從不引發異常並且從不丟失信息,以便可以在程序員不知曉的情況下安全使用它們。 如果轉換運算符不能滿足那些條件,則應將其標記為 explicit。
舉個例子
1 class A : IDisposable 2 { 3 public A(float f) 4 { 5 p = f; 6 } 7 8 public float p { get; } 9 10 public static implicit operator A(float f) 11 { 12 return new A(f); 13 } 14 15 public static implicit operator float(A a) 16 { 17 return a.p; 18 } 19 20 public static explicit operator B(A a) 21 { 22 return new B(a.p * 2); 23 } 24 25 26 27 public void Dispose() 28 { 29 } 30 } 31 32 class B 33 { 34 public B(float f) 35 { 36 p = f; 37 } 38 public float p { get; } 39 40 public static explicit operator A(B b) 41 { 42 return new A(b.p * 10f); 43 } 44 45 }
調用代碼
1 A a = null; 2 a?.Dispose(); 3 //初始化構造函數 4 a = new A(100.12345f); 5 //把a對象賦值給f,其實這個時候float已經被重載運算了所以不會報錯 6 float f = a; 7 //把30賦值給a2對象的時候,A類已被重載了 8 A a2 = 30; 9 Console.WriteLine( "f是:" + f + "\n"); 10 Console.WriteLine("a2.p是:" + a2.p + "\n"); 11 B b = (B)a; 12 Console.WriteLine("b.p是:" + b.p + "\n");
得到的結果是
f是:100.1235
a2.p是:30
b.p是:200.2469
總結:連續介紹了三個關鍵字operator搭配implicit和explicit,重載運算,類型轉換的過程當中都離不開static,explicit需要強制轉換而implicit隱試轉換類型。
---------------------
作者:鴻雁
來源:CSDN
原文:https://blog.csdn.net/w200221626/article/details/52413700
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!