强制转换对象为接口

本文通过一个具体例子演示了如何使用C#中的is运算符检查对象是否支持特定接口,并使用as运算符进行安全的类型转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可用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 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值