我一直以为base.Something
等同于((Parent)this).Something
,但显然并非如此。我认为重写方法消除了调用原始虚拟方法的可能性。
为什么第三项输出不同?
void Main() {
Child child = new Child();
child.Method(); //output "Child here!"
((Parent)child).Method(); //output "Child here!"
child.BaseMethod(); //output "Parent here!"
}
class Parent {
public virtual void Method() {
Console.WriteLine("Parent here!");
}
}
class Child : Parent {
public override void Method() {
Console.WriteLine ("Child here!");
}
public void BaseMethod() {
base.Method();
}
}
最佳答案
因为在BaseMethod
中,您通过使用base
关键字显式调用了基类中的方法。在类中调用Method()
和base.Method()
之间有区别。
在 base
关键字的文档中,它说(除其他事项外)它可以用来在已被另一个方法覆盖的基类上调用一个方法。
关于c# - 虚拟基础成员没有看到替代?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3612425/