在C#中实现多态性一般通过继承和接口实现。具体方法如下:
- 继承:通过创建一个父类和多个子类,子类继承父类的特性,并且可以重写父类的方法来实现多态性。例如:
class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal makes a sound");
}
}
class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog barks");
}
}
class Cat : Animal
{
public override void MakeSound()
{
Console.WriteLine("Cat meows");
}
}
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.MakeSound(); // Output: Dog barks
myCat.MakeSound(); // Output: Cat meows
- 接口:通过定义一个接口,然后让多个类实现这个接口,实现接口方法的多态性。例如:
interface IShape
{
double GetArea();
}
class Circle : IShape
{
public double Radius { get; set; }
public double GetArea()
{
return Math.PI * Radius * Radius;
}
}
class Rectangle : IShape
{
public double Width { get; set; }
public double Height { get; set; }
public double GetArea()
{
return Width * Height;
}
}
IShape myCircle = new Circle() { Radius = 5 };
IShape myRectangle = new Rectangle() { Width = 5, Height = 10 };
Console.WriteLine(myCircle.GetArea()); // Output: 78.54
Console.WriteLine(myRectangle.GetArea()); // Output: 50
通过以上两种方法,可以实现不同类对象对同一个方法的调用,实现多态性。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/916717.html