阅读:多态性(C# 编程指南)
类似的答案:编译时和运行时多态性
好吧,有两种类型的多态性,如下所述:
静态多态性(早期绑定):
静态多态性也称为早期绑定和编译时多态性。方法重载和运算符重载是相同的示例。
它被称为早期绑定,因为编译器知道具有相同名称的函数,并且在编译时也知道要调用哪个重载函数。
例如:
public class Test
{
public Test()
{
}
public int add(int no1, int no2)
{
}
public int add(int no1, int no2, int no3)
{
}
}
class Program
{
static void Main(string[] args)
{
Test tst = new Test();
int sum = tst.add(10, 20);
// here in above statement compiler is aware at compile time that need to call function add(int no1, int no2), hence it is called early binding and it is fixed so called static binding.
}
}
动态多态性(后期绑定):
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal sound");
}
}
public class Dog:Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog sound");
}
}
class Program
{
static void Main(string[] args)
{
Animal an = new Dog();
an.MakeSound();
Console.ReadLine();
}
}
和上面的代码一样,任何其他对虚拟方法的调用,都会被编译成一个 callvirt IL 指令。这意味着被调用的实际方法是在运行时确定的(除非 JIT 可以优化某些特殊情况),但是编译器检查了该方法是否存在,它选择了最合适的重载(如果有的话)并且它有保证函数指针将存在于该类型的 vtable 中明确定义的位置(即使这是一个实现细节)。解决虚拟调用的过程非常快(您只需要取消引用几个指针),因此没有太大区别。