定义:
接口是把公共实例(非静态)方法和属性组合起来,以封装特定功能的一个集合。接口是一种规范,也是一种能力
隐式实现接口
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 IPerson p = new Teacher(); 6 p.SayHello(); 7
8 Teacher t = new Teacher(); 9 t.SayHello(); 10
11 Console.ReadKey(); 12 } 13 } 14 class Teacher: IPerson 15 { 16 public void SayHello() 17 { 18 Console.WriteLine("Hello World!"); 19 } 20 } 21
22 interface IPerson 23 { 24 void SayHello(); 25 }
显示实现接口,目的:解决方法的重名问题
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 IPerson p = new Teacher(); 6 p.SayHello(); 7
8 Console.ReadKey(); 9 } 10 } 11 class Teacher: IPerson 12 { 13 void IPerson.SayHello() 14 { 15 Console.WriteLine("Hello World!"); 16 } 17 } 18
19 interface IPerson 20 { 21 void SayHello(); 22 }
隐式实现接口:可以用接口声明,也可以用实现类Teacher声明,调用者都可以得到实例化对象的行为SayHello;显示接口实现:SayHello方法只能通过接口来调用

隐式实现接口时,Teacher有而且必须有自己的访问修饰符(public)

显式实现接口时,Teacher不能有任何访问修饰符

当一个抽象类实现接口时,需要子类去实现接口
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 IPerson p = new TeacherSon(); 6 p.SayHello(); 7
8 Console.ReadKey(); 9 } 10 } 11 abstract class Teacher : IPerson 12 { 13 public void SayHello() 14 { 15 Console.WriteLine("Hello World!"); 16 } 17 } 18
19 class TeacherSon : Teacher 20 { 21
22 } 23
24 interface IPerson 25 { 26 void SayHello(); 27 }

注意
- 接口名一般以大写字母I开头
- 不能像实例化一个类一样实例化接口(不能new)
- 接口不能包含实现其成员的任何代码(不能有方法体)
- 接口中可以有方法、属性、索引器、事件,不能有字段、构造函数和静态成员
- 实现接口的子类必须实现该接口的全部成员
- 接口只能继承于接口
- 接口中成员不能有修饰符,默认为public