不忘本~explicit和implicit修饰符
生活随笔
收集整理的這篇文章主要介紹了
不忘本~explicit和implicit修饰符
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
返回目錄
部分內容來自MSDN
implicit 關鍵字用于聲明隱式的用戶定義類型轉換運算符。如果轉換過程可以確保不會造成數據丟失,則可使用該關鍵字在用戶定義類型和其他類型之間進行隱式轉換。
? 1 class Digit 2 3 { 4 5 public Digit(double d) { val = d; } 6 7 public double val; 8 9 10 11 12 13 // User-defined conversion from Digit to double 14 15 public static implicit operator double(Digit d) 16 17 { 18 19 return d.val; 20 21 } 22 23 // User-defined conversion from double to Digit 24 25 public static implicit operator Digit(double d) 26 27 { 28 29 return new Digit(d); 30 31 } 32 33 } 34 35 class Program 36 37 { 38 39 static void Main(string[] args) 40 41 { 42 43 Digit dig = new Digit(7); 44 45 //This call invokes the implicit "double" operator 46 47 double num = dig; 48 49 //This call invokes the implicit "Digit" operator 50 51 Digit dig2 = 12; 52 53 Console.WriteLine("num = {0} dig2 = {1}", num, dig2.val); 54 55 Console.ReadLine(); 56 57 } 58 59 }?
explicit 關鍵字用于聲明必須使用強制轉換來調用的用戶定義的類型轉換運算符
1 // cs_keyword_explicit_temp.cs 2 using System; 3 class Celsius 4 { 5 public Celsius(float temp) 6 { 7 degrees = temp; 8 } 9 public static explicit operator Fahrenheit(Celsius c) 10 { 11 return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32); 12 } 13 public float Degrees 14 { 15 get { return degrees; } 16 } 17 private float degrees; 18 } 19 20 class Fahrenheit 21 { 22 public Fahrenheit(float temp) 23 { 24 degrees = temp; 25 } 26 public static explicit operator Celsius(Fahrenheit f) 27 { 28 return new Celsius((5.0f / 9.0f) * (f.degrees - 32)); 29 } 30 public float Degrees 31 { 32 get { return degrees; } 33 } 34 private float degrees; 35 } 36 37 class MainClass 38 { 39 static void Main() 40 { 41 Fahrenheit f = new Fahrenheit(100.0f); 42 Console.Write("{0} fahrenheit", f.Degrees); 43 Celsius c = (Celsius)f; 44 Console.Write(" = {0} celsius", c.Degrees); 45 Fahrenheit f2 = (Fahrenheit)c; 46 Console.WriteLine(" = {0} fahrenheit", f2.Degrees); 47 } 48 }?
返回目錄
總結
以上是生活随笔為你收集整理的不忘本~explicit和implicit修饰符的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 戴睿笔记本为什么便宜(汉典戴字的基本解释
- 下一篇: prt文件怎么打开(什么软件能打开prt