不忘本~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 }

 

返回目录

posted @ 2011-07-12 17:46  张占岭  阅读(1148)  评论(0编辑  收藏  举报