显式接口实现还允许程序员继承共享相同成员名的两个接口,并为每个接口成员提供一个单独的实现。下面是关于这方面的示例:
1
//版权所有 (C) 2000 Microsoft Corporation。保留所有权利。
2
3
// explicit2.cs
4
// 声明英制单位接口:
5
interface IEnglishDimensions
6

{
7
float Length();
8
float Width();
9
}
10
// 声明公制单位接口:
11
interface IMetricDimensions
12

{
13
float Length();
14
float Width();
15
}
16
// 声明实现以下两个接口的“Box”类:
17
// IEnglishDimensions 和 IMetricDimensions:
18
class Box : IEnglishDimensions, IMetricDimensions
19

{
20
float lengthInches;
21
float widthInches;
22
public Box(float length, float width)
23
{
24
lengthInches = length;
25
widthInches = width;
26
}
27
// 显式实现 IEnglishDimensions 的成员:
28
float IEnglishDimensions.Length()
29
{
30
return lengthInches;
31
}
32
float IEnglishDimensions.Width()
33
{
34
return widthInches;
35
}
36
// 显式实现 IMetricDimensions 的成员:
37
float IMetricDimensions.Length()
38
{
39
return lengthInches * 2.54f;
40
}
41
float IMetricDimensions.Width()
42
{
43
return widthInches * 2.54f;
44
}
45
public static void Main()
46
{
47
// 声明类实例“myBox”:
48
Box myBox = new Box(30.0f, 20.0f);
49
// 声明英制单位接口的实例:
50
IEnglishDimensions eDimensions = (IEnglishDimensions) myBox;
51
// 声明公制单位接口的实例:
52
IMetricDimensions mDimensions = (IMetricDimensions) myBox;
53
// 以英制单位打印尺寸:
54
System.Console.WriteLine("Length(in): {0}", eDimensions.Length());
55
System.Console.WriteLine("Width (in): {0}", eDimensions.Width());
56
// 以公制单位打印尺寸:
57
System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
58
System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());
59
}
60
}
61
输出
2

3

4

5

6



7

8

9

10

11

12



13

14

15

16

17

18

19



20

21

22

23



24

25

26

27

28

29



30

31

32

33



34

35

36

37

38



39

40

41

42



43

44

45

46



47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

Length(in): 30
Width (in): 20
Length(cm): 76.2
Width (cm): 50.8
代码讨论
如果希望默认度量采用英制单位,请正常实现 Length 和 Width 这两个方法,并从 IMetricDimensions 接口显式实现 Length 和 Width 方法:



























System.Console.WriteLine("Length(in): {0}", myBox.Length());
System.Console.WriteLine("Width (in): {0}", myBox.Width());
System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());