How to use reflection call a base method that is overridden by derived class?
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();
}
This code always shows 'Derived'...
Maybe Kii was looking for something like this
You can't do that, even with reflection. Polymorphism in C# actually guarantees that
Derived.Foo()
will always be called, even on an instance ofDerived
cast back to its base class.The only way to call
Base.Foo()
from aDerived
instance is to explicitly make it accessible from theDerived
class: