如何使用反射调用被派生类覆盖的基本方法?
class Base { public virtual void Foo() { Console.WriteLine("Base"); } } class Derived : Base { public override void Foo() { Console.WriteLine("Derived"); } } public static void Main() { Derived d = new Derived(); typeof(Base).GetMethod("Foo").Invoke(d, null); Console.ReadLine(); }
此代码始终显示“派生” …
即使反射,也无法做到。实际上Derived.Foo(),即使在Derived强制转换回其基类的实例上,C#中的多态实际上也保证始终会调用它。
Derived.Foo()
Derived
Base.Foo()从Derived实例调用的唯一方法是显式使其可从Derived类访问:
Base.Foo()
class Derived : Base { public override void Foo() { Console.WriteLine("Derived"); } public void BaseFoo() { base.Foo(); } }