在C#中实现多态性一般通过继承和接口实现。具体方法如下
在C#中实现多态性一般通过继承和接口实现。具体方法如下:
- 继承:通过创建一个父类和多个子类,子类继承父类的特性,并且可以重写父类的方法来实现多态性。例如:
classAnimal
{
publicvirtualvoidMakeSound()
{
Console.WriteLine("Animalmakesasound");
}
}
classDog:Animal
{
publicoverridevoidMakeSound()
{
Console.WriteLine("Dogbarks");
}
}
classCat:Animal
{
publicoverridevoidMakeSound()
{
Console.WriteLine("Catmeows");
}
}
AnimalmyDog=newDog();
AnimalmyCat=newCat();
myDog.MakeSound();//Output:Dogbarks
myCat.MakeSound();//Output:Catmeows
interfaceIShape
{
doubleGetArea();
}
classCircle:IShape
{
publicdoubleRadius{get;set;}
publicdoubleGetArea()
{
returnMath.PI*Radius*Radius;
}
}
classRectangle:IShape
{
publicdoubleWidth{get;set;}
publicdoubleHeight{get;set;}
publicdoubleGetArea()
{
returnWidth*Height;
}
}
IShapemyCircle=newCircle(){Radius=5};
IShapemyRectangle=newRectangle(){Width=5,Height=10};
Console.WriteLine(myCircle.GetArea());//Output:78.54
Console.WriteLine(myRectangle.GetArea());//Output:50
通过以上两种方法,可以实现不同类对象对同一个方法的调用,实现多态性。
版权声明
本文仅代表作者观点,不代表博信信息网立场。