可用is运算符检查是否支持接口,用as运算符转换接口,如:
1 /*
2 Example8_4.cs illustrates casting an object
3 to an interface
4 */
5
6 using System;
7
8
9 // define the IDrivable interface
10 public interface IDrivable
11 {
12
13 // method declarations
14 void Start();
15 void Stop();
16
17 // property declaration
18 bool Started
19 {
20 get;
21 }
22
23 }
24
25
26 // Car class implements the IDrivable interface
27 public class Car : IDrivable
28 {
29
30 // declare the underlying field used by the Started property
31 private bool started = false;
32
33 // implement the Start() method
34 public void Start()
35 {
36 Console.WriteLine("car started");
37 started = true;
38 }
39
40 // implement the Stop() method
41 public void Stop()
42 {
43 Console.WriteLine("car stopped");
44 started = false;
45 }
46
47 // implement the Started property
48 public bool Started
49 {
50 get
51 {
52 return started;
53 }
54 }
55
56 }
57
58
59 class Example8_4
60 {
61
62 public static void Main()
63 {
64
65 // create a Car object
66 Car myCar = new Car();
67
68 // use the is operator to check that myCar supports the
69 // IDrivable interface
70 if (myCar is IDrivable)
71 {
72 Console.WriteLine("myCar supports IDrivable");
73 }
74
75 // cast the Car object to IDrivable
76 IDrivable myDrivable = (IDrivable) myCar;
77
78 // call myDrivable.Start()
79 Console.WriteLine("Calling myDrivable.Start()");
80 myDrivable.Start();
81 Console.WriteLine("myDrivable.Started = " +
82 myDrivable.Started);
83
84 // call myDrivable.Stop()
85 Console.WriteLine("Calling myDrivable.Stop()");
86 myDrivable.Stop();
87 Console.WriteLine("myDrivable.Started = " +
88 myDrivable.Started);
89
90 // cast the Car object to IDrivable using the as operator
91 IDrivable myDrivable2 = myCar as IDrivable;
92 if (myDrivable2 != null)
93 {
94 Console.WriteLine("Calling myDrivable2.Start()");
95 myDrivable2.Start();
96 Console.WriteLine("Calling myDrivable2.Stop()");
97 myDrivable2.Stop();
98 Console.WriteLine("myDrivable2.Started = " +
99 myDrivable2.Started);
100 }
101
102 }
103
104 }