如何覆盖虚方法,但仍然在C#中调用基类版本

Kan*_* Su 0 c# types casting upcasting

我有一个简单的类层次结构,我有一个覆盖的虚方法.但在某些调用中我想调用此方法的基类版本而不是虚方法.

例如:

public class A {
    public virtual void Foo() {...}
}

public class B : A {
    public override void Foo() {...}
}

public class Program {
    public void SomeMethod()
    {
       ...

       //  ListofA is type IEnumerable<A>
       foreach (var item in ListofA)
       {
           // I want this to call A.Foo(), rather than B.Foo()
           // But everything I've tried, which has really just been casting, has resulted in B.Foo()
           item.Foo();
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*are 8

你无法覆盖.覆盖替换原始(从呼叫者的角度来看).重写的方法可以调用基础,但不能从外部调用.