我无法弄清楚该方法调用的具体原因,多级继承的情况下,当存在多个virtual和override时,如何知道将调用哪个方法?
public class A
{
public virtual void f1()
{
Console.WriteLine("A");
}
}
public class B:A
{
public override void f1()
{
Console.WriteLine("B");
}
}
public class C:B
{
public override void f1()
{
Console.WriteLine("C");
}
}
public class D:C
{
public virtual void f1()
{
Console.WriteLine("D");
}
}
public class E : D
{
public override void f1()
{
Console.WriteLine("E");
}
}
A aobj = new D();
aobj.f1();
//why output is "C" here
A aobj = new E();
aobj.f1();
//why output is again "C" and not "E"
我很困惑,需要其他人的帮助来理解,编译器如何决定调用哪个函数?
最佳答案
在您的示例中,virtual
关键字用于 D.f1()
,而不是override
。无需将 D.f1()
标记为 virtual
,因为基本方法 A.f1()
已经是虚拟的。
我不确定您是否注意到您当前的代码抛出了 CS0114
警告:
CS0114: 'D.f1()' hides inherited member 'C.f1()'.
To make the current member override that implementation, add the override keyword.
Otherwise add the new keyword.
将 class D
更改为以下内容将更正该问题:
public class D:C
{
public override void f1() // Notice use of 'override' instead of 'virtual'
{
Console.WriteLine("D");
}
}
经过上述更改,返回预期输出:
D
E
看一下这两个讨论非常相似问题的问题:
- Resolving the "most derived" method in a virtual override
- What if I don't heed the warning "hides inherited member. To make the current member override that implementation...."
编辑:行为背后的基本原理
aobj
是A 类
的实例。因此,从基类 A 向上进行工作以确定调用的是哪个版本的 f1()
。 最高重写方法是C.f1()
,因此将调用它。 D 类中的重写层次结构已通过使用 virtual
被破坏,因此 D.f1()
和 E.f1()
不是使用类 A
的实例时调用。
关于c# - 如何知道 virtual\override 中的大多数派生实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42883453/