在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
通過以上兩種方法,可以實現不同類對象對同一個方法的調用,實現多態性。