12.8 接口的派生
和类一样,接口也可以从基接口派生,但和类的派生也有很大的不同:类不能继承多个类,而接口可以继承多个接口。如果要从多个接口继承,这些基接口之间只需使用逗号进行分隔即可。
接下来使用例子来说明。先声明两个接口ISample和ISample2,然后再声明一个接口ISample3,它继承自前面声明的两个接口ISample和ISample2,然后定义一个类ClassTree,它实现接口ISample3,如代码清单12-12所示。
代码清单12-12 接口的派生
1 interface ISample
2{
3 void Method1();
4}
5
6 interface ISample2
7{
8 void Method2();
9}
10
11 interface ISample3:ISample,ISample2//从其他接口派生
12{
13 void Method3();
14}
15
16 class ClassTree:ISample3//需要实现所有接口定义的成员
17{
18 public void Method1()//ISample接口中定义的成员
19{
20 System.Console.WriteLine("from ClassTree.Method1()");
21}
22
23 public void Method2()//ISample2接口中定义的成员
24{
25 System.Console.WriteLine("from ClassTree.Method2()");
26}
27
28 public void Method3()//ISample3接口中定义的成员
29{
30 System.Console.WriteLine("from ClassTree.Method3()");
31}
32}
33
34 class ClassExample
35{
36 public static void Main()
37{
38 ClassTree clsTree=new ClassTree();
39 clsTree.Method1();
40 clsTree.Method2();
41 clsTree.Method3();
42
43 ISample sample1=(ISample)clsTree;
44 ISample2 sample2=(ISample2)clsTree;
45 ISample3 sample3=(ISample3)clsTree;
46 sample1.Method1();
47 sample2.Method2();
48//ISample3接口派生自ISample和ISample2
49//因此ISample3接口继承了基接口定义的成员
50 sample3.Method1();
51 sample3.Method2();
52 sample3.Method3();
53}
54}
上述代码运行的结果为:
from ClassTree.Method1()
from ClassTree.Method2()
from ClassTree.Method3()
from ClassTree.Method1()
from ClassTree.Method2()
from ClassTree.Method1()
from ClassTree.Method2()
from ClassTree.Method3()