- 定义一个接口在语法上跟定义一个抽象类完全相同,但不允许提供接口中任何成员的实现方式,一般情况下,接口只能包含方法,属性,索引器和事件的声明。
- 接口不能有构造函数,也不能有字段,接口也不允许运算符重载。
- 接口定义中不允许声明成员的修饰符,接口成员都是公有的
- 接口可以多实现,类的继承只能有一个
internal interface IFly
{
void Fly();
void FlyAttack();
}
internal class Bird : IFly
{
public void Fly()
{
Console.WriteLine("小鸟在空中飞");
}
public void FlyAttack()
{
Console.WriteLine("小鸟在空中攻击");
}
}
internal class Plane : IFly
{
public void Fly()
{
Console.WriteLine("飞机在空中飞");
}
public void FlyAttack()
{
Console.WriteLine("在空中攻击");
}
}
测试
namespace _13_接口
{
internal class Program
{
static void Main(string[] args)
{
Plane plane = new Plane()
plane.Fly()
plane.FlyAttack()
//接口不能实现,但可以声明,类似父类声明,子类构造,这种也叫多态
IFly fly
fly = new Plane()
fly.Fly()
fly.FlyAttack()
//这里fly就是多态
fly = new Bird()
fly.Fly()
fly.FlyAttack()
}
}
}
接口的继承
- 接口可以继承另一个接口
- 一个类可以继承多个接口,实现多个接口,但只能继承一个类
internal interface Interface1
{
void Method1();
}
internal interface Interface2:Interface1
{
void Method2();
}
internal class Class1 : Bird, Interface1, Interface2
{
public void Method1()
{
throw new NotImplementedException();
}
public void Method2()
{
throw new NotImplementedException();
}
}