通过base调用父类虚函数的问题
dobly 2005-12-14 09:15:51 using System;
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee: Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass {
public static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
输出
Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG
我的疑问是,为何子类Employee调用父类的虚函数(base.GetInfo();)时,根据多态原则,Person类不会去查找其子类的方法Employee.GetInfo()?
MSDN里作了如下说明:
当某个 base 访问引用虚函数成员(方法、属性或索引器)时,确定在运行时调用哪个函数成员的规则有一些更改。确定调用哪一个函数成员的方法是,查找该函数成员相对于 B(而不是相对于 this 的运行时类型,在非 base 访问中通常如此)的派生程度最大的实现。因此,在 virtual 函数成员的 override 中,可以使用 base 访问调用该函数成员的被继承了的实现。如果 base 访问引用的函数成员是抽象的,则发生编译时错误。
各位有何见解?