用法
接口为所有抽象行为的“基类”。 为什么这么说呢,比如飞机类和鸟类,两者没有关系,但是飞机和鸟都拥有飞这个行为,就都去继承飞这个接口,但两者飞的动作肯定也不一样,也是多态的体现。
申明的规范:
1.不能包含成员变量
2.只包含方法,成员属性,索引器,事件
3.成员不能被实现
4.成员修饰符默认为public,不能为私有
5.接口不能继承类,但是可以继承另一个接口
6.类继承接口后,必须实现接口中所有成员
特点:
1.接口不能被实例化
2.可以作为容器存储对象,也就是满足里氏替换原则
接口语法
interface 接口名
{
}
命名规范:帕斯卡命名前面加I
接口的使用:
1.类可以继承1个类,多个接口
2.实现该接口里的成员时,必须用public
3.接口满足里氏替换原则
例子:
interface IFly
{
void Fly();
string Name
{
get;
set;
}
int this[int index]
{
get;
set;
}
event Action doSomething;
}
class Animal
{
}
class Person : Animal, IFly
{
public int this[int index]
{ get
{
return 0;
}
set
{
}
}
public string Name
{
get
{
return "";
}
set
{
}
}
public event Action doSomething;
public void Fly()
{
}
}
class Program
{
static void Main(string[] args)
{
//里氏替换原则
IFly f = new Person();
Console.ReadKey();
}
}
接口继承接口
接口继承接口,不需要实现,当类继承后,要实现所有接口的内容。
例子:
interface IFly :IMove
{
void Fly();
void Speed();
}
interface IMove
{
}
interface IWalk:IMove
{
void walk();
}
class Player : IWalk, IFly
{
public void Fly()
{
}
public void Speed()
{
}
public void walk()
{
}
}
显示实现接口
当一个类继承两个接口,存在同名方法时。
注意:显示实现接口,不能写修饰符。
例子:
interface IAtk
{
void Atk();
}
interface ISuperAtk
{
void Atk();
}
class Player : IAtk, ISuperAtk
{
//用接口名.行为名
void IAtk.Atk()
{
Console.WriteLine("普通攻击");
}
void ISuperAtk.Atk()
{
Console.WriteLine("超级攻击");
}
public void Atk()
{
Console.WriteLine("玩家攻击");
}
}
class Program
{
static void Main(string[] args)
{
//里氏替换原则
IAtk iatk = new Player();
ISuperAtk superAtk = new Player();
Player player = new Player();
iatk.Atk();
superAtk.Atk();
player.Atk();
Console.ReadKey();
}
}
抽象类与接口的区别
相同点
1.都可以被继承
2.都不能直接实例化
3.都可以包含方法声明
4.子类必须实现未实现的方法
5.都遵循里氏替换原则
不同点
1.抽象类可以有构造函数,而接口没有
2.抽象类只能单一继承,接口可以多个
3.抽象类可以有成员变量,接口不能
4.接口只能申明没有实现的抽象方法,而抽象类都可以
表示对象用抽象类,表示行为用接口。