
返回目录
部分内容来自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 }欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)