转自原文C#接口的三种实现方式
1
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
|
public
interface
MyInterface
{
/// 下面三个方法的签名都是
/// .method public hidebysig newslot abstract virtual
/// public+virutal+abstract
void
Method1();
void
Method2();
void
Method3();
}
class
MyClass : MyInterface
{
/// Method1是Non-overridable的实现,是sealed。签名如下
/// .method public final hidebysig newslot virtual
/// 注意:public+final+virtual
public
void
Method1() { }
/// Method2是Overridable的实现。签名如下
/// .method public hidebysig newslot virtual
/// 注意:public+virtual
public
virtual
void
Method2() { }
/// Method3是Explicit的实现,是sealed。签名如下
/// .method private final hidebysig newslot virtual
/// 注意:private+final+virual
void
MyInterface.Method3() { }
}
class
MyDerived : MyClass
{
/// .method public hidebysig
/// Hidden了MyClass的Method1,所以要加new,否则warning
public
new
void
Method1() { }
/// .method public hidebysig virtual
public
override
void
Method2() { }
/// .method private hidebysig
void
Method3() { }
}
|
总结:
Method2的实现是最常见的。
Method1的实现变成了sealed,用在不想被override的地方。
Method3的实现比较少见,一种情况是类实例不想对外暴露(private),但是在使用接口的地方又可以访问;另一种是在继承多个接口时,多个接口中相同的函数签名。
MyInterface myclass = new MyClass(); myclass.Method3(); // OK