多态

多态让你用“统一的方式”去操作“不同的对象”,而每个对象会做出“自己特有的反应”。
就像:
你喊一声“开始工作”,程序员会敲代码,厨师会炒菜,司机会开车。
你不用管具体是谁,只要喊“开始工作”,他们就会自动做自己该做的事

——————————————————————————————————————————————————————————————————————————————

案例1:动物叫声(最经典)
csharp
class Animal { public virtual void Speak() { Console.WriteLine("动物叫"); } }
class Dog : Animal { public override void Speak() { Console.WriteLine("汪汪"); } }
class Cat : Animal { public override void Speak() { Console.WriteLine("喵喵"); } }

class Program
{
static void Main()
{
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.Speak(); // 汪汪
a2.Speak(); // 喵喵
}
}
都是Animal类型,但调用Speak()时,狗叫汪汪,猫叫喵喵。

————————————————————————————————————————————————————————————————————————————

案例2:不同形状算面积
csharp
class Shape { public virtual double Area() { return 0; } }
class Circle : Shape { public double R; public override double Area() { return 3.14 * R * R; } }
class Rect : Shape { public double W, H; public override double Area() { return W * H; } }

class Program
{
static void Main()
{
Shape s1 = new Circle { R = 5 };
Shape s2 = new Rect { W = 4, H = 6 };
Console.WriteLine(s1.Area()); // 78.5
Console.WriteLine(s2.Area()); // 24
}
}
不管圆形还是矩形,统一用Area()计算,各自算自己的公式。

————————————————————————————————————————————————————————————————————————————

案例3:员工发工资(更实用)
csharp
class Employee { public virtual int GetPay() { return 3000; } }
class Manager : Employee { public override int GetPay() { return 8000; } }
class Intern : Employee { public override int GetPay() { return 1500; } }

class Program
{
static void Main()
{
Employee[] staff = { new Manager(), new Intern(), new Employee() };
foreach (var e in staff)
Console.WriteLine(e.GetPay()); // 8000, 1500, 3000
}
}
遍历员工数组,不用判断类型,直接发工资,各拿各的。

posted @ 2026-08-07 13:11  菜鸟的奋斗军  阅读(4)  评论(0)    收藏  举报