在 C# 中,我可以这样做:
class Program
{
static void Main(string[] args)
{
List<Animal> animals = new List<Animal>();
animals.Add(new Dog());
animals.Add(new Cat());
foreach (Animal a in animals)
{
Console.WriteLine(a.MakeNoise());
a.Sleep();
}
}
}
public class Animal
{
public virtual string MakeNoise() { return String.Empty; }
public void Sleep()
{
Console.Writeline(this.GetType().ToString() + " is sleeping.");
}
}
public class Dog : Animal
{
public override string MakeNoise()
{
return "Woof!";
}
}
public class Cat : Animal
{
public override string MakeNoise()
{
return "Meow!";
}
}
显然,输出是(稍微解释一下):
- 纬
- 狗在睡觉
- 喵
- 猫在睡觉
由于 C# 经常因其冗长的类型语法而受到嘲笑,您如何处理诸如 Ruby 之类的鸭子类型语言中的多态性/虚拟方法?