- 什么是接口? 接口是包含一组虚方法的抽象类型,其中每一种方法都有其名称、参数和返回值。接口方法不能包含任何实现部分。C#中接口可以包含属性、方法、索引器和事件声明。当某个类实现(implement)某个接口时候,这个类必须实现接口中的所有方法和其他成员。接口不能实例化。
- 什么是抽象类? 抽象类提供多个派生类共享基类的公共定义,它既可以提供抽象方法,也可以提供非抽象方法。抽象类不能实例化,必须通过继承由派生类实现其抽象方法,因此对抽象类不能使用new关键字,也不能被密封。如果派生类没有实现所有的抽象方法,则该派生类也必须声明为抽象类。另外,实现抽象方法由overriding方法来实现。
接口和抽象类的区别:
- 抽象类应主要用于关系密切的对象,是对具有相同特点的一类(族)事物的抽象,更加注重与这些事物的共同属性等。比如:猫(Cat)、狗(Dog)、鸟(Bird)等几类,就可以抽象为Animal抽象类,他们具有共同的特征比如嘴巴、眼睛、耳朵、脚等属性,也都有Eat吃东西的功能。Cat、Dog、Pig继承自Animal抽象类,也就具有这些属性。 因此抽象类强调的是一种IS-A的关系;为此我们可以有以下实现。
View Code
1 abstract class Animal
2 {
3 public abstract string Mouth { get; set; }
4 public abstract string Eye { get; set; }
5 public abstract string Ear { get; set; }
6 public abstract void EatFoot();
7 }
8
9 class Cat : Animal
10 {
11 public override string Mouth
12 {
13 get;
14 set;
15 }
16
17 public override string Eye
18 {
19 get;
20 set;
21 }
22
23 public override string Ear
24 {
25 get;
26 set;
27 }
28
29 public override void EatFoot()
30 {
31 Console.WriteLine("Eat Fish");
32 }
33 }
34
35 class Dog : Animal
36 {
37 public override string Mouth
38 {
39 get;
40 set;
41 }
42
43 public override string Eye
44 {
45 get;
46 set;
47 }
48
49 public override string Ear
50 {
51 get;
52 set;
53 }
54
55 public override void EatFoot()
56 {
57 Console.WriteLine("Eat Bone");
58 }
59 }
60
61 class Bird : Animal
62 {
63 public override string Mouth
64 {
65 get;
66 set;
67 }
68
69 public override string Eye
70 {
71 get;
72 set;
73 }
74
75 public override string Ear
76 {
77 get;
78 set;
79 }
80
81 public override void EatFoot()
82 {
83 Console.WriteLine("Eat worm");
84 }
85 } - 接口主要是定义一种规范或者行为,为不相关的对象提供统一标准的功能。比如Bird鸟类会Fly,而飞机也会Fly,他们之前并不属于同一种抽象类型,但是都有Fly的功能。因此,我们可以定义一个IFly接口具有Fly的功能;然后飞机和Bird都实现这个接口。因此,接口是对功能、行为的抽象,更强调一种“Can do”的关系。
View Code在设计接口时候,尽量将接口设计成功能单一的功能块,要避免引起接口污染。“接口不变”是应该考虑的重要因素。在由接口增加扩展功能时候,应该增加新的接口,而不是更改现有接口。
1 interface IFly
2 {
3 void Fly();
4 }
5
6 class Plane : IFly
7 {
8 #region IFly 成员
9
10 public void Fly()
11 {
12 Console.WriteLine("Plane: I can fly with my iron wings");
13 }
14
15 #endregion
16 }
17
18 class Bird : Animal,IFly
19 {
20 public override string Mouth
21 {
22 get;
23 set;
24 }
25
26 public override string Eye
27 {
28 get;
29 set;
30 }
31
32 public override string Ear
33 {
34 get;
35 set;
36 }
37
38 public override void EatFoot()
39 {
40 Console.WriteLine("Eat worm");
41 }
42
43 #region IFly 成员
44
45 public void Fly()
46 {
47 Console.WriteLine("Bird:I can fly with my two wings");
48 }
49
50 #endregion
51 }