如下面的IDrivable和IStreerable都声明了TurnLeft()方法
public interface IDrivable
{
void TurnLeft();
}
public interface IStreerable
{
void TurnLeft();
}
如果声明一个类实现这两个接口,在类中必须定义两个TurnLeft()方法,如何区别这两个方法呢?答案是:必须显示声明这个方法属于哪个接口,如下例:
1 /*
2 Example8_7.cs illustrates an explicit interface member
3 implementation
4 */
5
6 using System;
7
8
9 // define the IDrivable interface
10 public interface IDrivable
11 {
12 void TurnLeft();
13 }
14
15
16 // define the ISteerable interface
17 public interface ISteerable
18 {
19 void TurnLeft();
20 }
21
22 // Car class implements the IMovable interface
23 public class Car : IDrivable, ISteerable
24 {
25
26 // explicitly implement the TurnLeft() method of the IDrivable interface
27 void IDrivable.TurnLeft()
28 {
29 Console.WriteLine("IDrivable implementation of TurnLeft()");
30 }
31
32 // implement the TurnLeft() method of the ISteerable interface
33 public void TurnLeft()
34 {
35 Console.WriteLine("ISteerable implementation of TurnLeft()");
36 }
37
38 }
39
40
41 class Example8_7
42 {
43
44 public static void Main()
45 {
46
47 // create a Car object
48 Car myCar = new Car();
49
50 // call myCar.TurnLeft()
51 Console.WriteLine("Calling myCar.TurnLeft()");
52 myCar.TurnLeft();
53
54 // cast myCar to IDrivable
55 IDrivable myDrivable = myCar as IDrivable;
56 Console.WriteLine("Calling myDrivable.TurnLeft()");
57 myDrivable.TurnLeft();
58
59 // cast myCar to ISteerable
60 ISteerable mySteerable = myCar as ISteerable;
61 Console.WriteLine("Calling mySteerable.TurnLeft()");
62 mySteerable.TurnLeft();
63
64 }
65
66 }