虚拟基础成员没有看到覆盖?

rec*_*ive 5 c# inheritance

我一直认为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(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

Fre*_*örk 5

因为在BaseMethod明确地调用基类中的方法,通过使用base关键字.在课堂上Method()base.Method()课堂之间有区别.

base关键字的文档中,它说(除其他外)它可以用于调用已被另一个方法覆盖的基类上的方法.