也许有人会对使用动态关键字 (MSDN blog) 进行多次调度的良好 C# 示例 感兴趣
class Animal
{
}
class Cat : Animal
{
}
class Dog : Animal
{
}
class Mouse : Animal
{
}
我们可以为同一个方法创建多个重载,根据其参数类型的不同组合进行专门化:
void ReactSpecialization(Animal me, Animal other)
{
Console.WriteLine("{0} is not interested in {1}.", me, other);
}
void ReactSpecialization(Cat me, Dog other)
{
Console.WriteLine("Cat runs away from dog.");
}
void ReactSpecialization(Cat me, Mouse other)
{
Console.WriteLine("Cat chases mouse.");
}
void ReactSpecialization(Dog me, Cat other)
{
Console.WriteLine("Dog chases cat.");
}
现在是神奇的部分:
void React(Animal me, Animal other)
{
ReactSpecialization(me as dynamic, other as dynamic);
}
这是因为“动态”强制转换,它告诉 C# 编译器,而不是仅仅调用 ReactSpecialization(Animal, Animal),动态检查每个参数的类型并在运行时选择要调用的方法重载.
为了证明它确实有效:
void Test()
{
Animal cat = new Cat();
Animal dog = new Dog();
Animal mouse = new Mouse();
React(cat, dog);
React(cat, mouse);
React(dog, cat);
React(dog, mouse);
}
输出:
Cat runs away from dog.
Cat chases mouse.
Dog chases cat.
Dog is not interested in Mouse.
维基百科说 C# 4.0(动态)是“多调度”语言。
我也认为 Java、C#(4.0 之前)、C++ 等语言是单调度的。