接口是一种规范。
语法:接口
[public] interface I..able
{
成员;
}
只要一个类继承了一个接口,这个类就必须实现这个接口中所有的成员
接口并不能去继承一个类,而类可以继承接口 (接口只能继承于接口,而类既可以继承接口,也可以继承类)
显示实现接口的目的:解决方法的重名问题
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 |
class Program { static void Main(string[] args) { IFlyable fly = new Bird();//new Person();// new IFlyable(); fly.Fly(); Console.ReadKey(); } } public class Person:IFlyable { public void Fly() { Console.WriteLine("人类在飞"); } } public class Student:Person,IFlyable //先继承父类在继承接口 { public void Fly() { Console.WriteLine("人类在飞"); } } public class Bird : IFlyable { public void Fly() { Console.WriteLine("鸟在飞"); } } public interface IFlyable { //不允许有访问修饰符 默认为public //方法、自动属性 void Fly();//接口中的成员不能有任何实现 } |
为了多态。
接口、抽象类、静态类不能被实例化。
也就是说,接口不能new(不能创建对象)
接口中的成员不能加“访问修饰符”,接口中的成员访问修饰符为public,不能修改。
(默认为public)
接口中只能有方法、属性、索引器、事件,不能有“字段”和构造函数。
接口与接口之间可以继承,并且可以多继承。(接口中的成员不能有任何实现(“光说不做”,只是定义了一组未实现的成员)
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 |
例: public interface M1 { void Test1(); } public interface M2 { void Test2(); } public interface M3 { void Test3(); } public interface SupperInterface : M1, M2, M3 { } public class Car : SupperInterface//在类中实现接口 { public void Test1() { throw new NotImplementedException(); } public void Test2() { throw new NotImplementedException(); } public void Test3() { throw new NotImplementedException(); } } |
**显示实现接口**
显示实现接口的目的:解决方法的重名问题
什么时候显示的去实现接口:
当继承的借口中的方法和参数一摸一样的时候,要是用显示的实现接口
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 |
class Program { static void Main(string[] args) { //显示实现接口就是为了解决方法的重名问题 IFlyable fly = new Bird(); fly.Fly();//调用接口的fly(); Bird bird = new Bird(); bird.Fly();//调用自己的fly() Console.ReadKey(); } } public class Bird : IFlyable { public void Fly() { Console.WriteLine("鸟飞会"); } /// <summary> /// 显示实现接口 /// </summary> void IFlyable.Fly()//强调调用接口的方法 { Console.WriteLine("我是接口的飞"); } } public interface IFlyable { void Fly(); } |