c#接口、抽象类

1、定义接口

interface ILandBound
{
int NumberOfLegs();//不需要设置访问修饰符
}

class Horse : ILandBound
{
public int NumberOfLegs();//实现时public
}

2、实现接口

interface ILandBound
{
.......
}
class Mammal
{
.......
}
class Hourse:Mammal,ILandBund//父类名在前,接口名在后
{
.......
}
class Hourse:Mammal,ILANDbOUND,IGrab//只能继承一个父类但可以实现多个接口
{
.......
}

3、通过接口引用类对象

Horse myHorse = new Horse();
ILandBoundiMyHorse = myHorse;
int FindLandSpeed(IlandBound  landBoundMamal)
{
..
}

4、实现多个接口的特例

interface ILandBound
{
int NumberOfLegs();
}
interface IJourney
{
int NumberOfLegs();
}
class Horse : ILandBound,IJourney//实现多个接口同名方法
{
int ILandBound.NumberOfLegs()
{
return 3;
}
int IJourney.NumberOfLegs()
{
return 4;
}

}

Horse horse = new Horse();
IJourney journeyHorse=horse;
int legslnJourney = journeyHorse.NumberOfLegs();

5、抽象类

抽象方法默认就是virtual(虚方法)

抽象方法没有方法体,abstract关键字声明

子类继承实现

抽象类不能被实现

6、密封类不能被继承,关键字sealed声明 sealed class

原文地址:https://www.cnblogs.com/lujianwei/p/2559171.html