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'...
This can be achieved through Code emit
http://blogs.msdn.com/b/rmbyers/archive/2008/08/16/invoking-a-virtual-method-non-virtually.aspx
Even though the current answer is already accepted, it's actually possible without having to change the original class by using a dynamic method like this:
as you can see it's still relatively simple to do
Reflection allows you to see that the object d has a "Foo" method and also to invoke it.
This method however is a virtual method and that's why you're getting the implementation of that method by a Derived class since that is what d is (in addition to also being castable to a Base).
There is no [direct] way to invoke the Base's virtual methods from a Derived object.
As shown in in Frederic Hamidi's, the Base class' method can be exposed by the Derived class (under a different name), but that's not really invoking the Base's method, it is invoking a method of the Derived class which happens to call the Base's method.
Although this approach of having the Derived class supply a "proxy" to the method of the Base class, ultimately does what you ask for, it is probably a bad idea to do this: there's likely a flaw in the design of your object model: it would be a rather odd use case...
1)Casting cannot change it's class type.
2) Above are invalid, because you never created any
Base
object instance when you createdDerived
object instance. You created instance object ofDerived class
which inherited fromBase class
. Hope, that explains why you could not invoke base function with derived objectAfter a long time, I finally find a better solution than DynamicMethod:
This solution use the standard constructor signature of delegate:
where target is the target instance and ftn is the function pointer. It directly invoke it with the function pointer of base method, so the delegate will point to the actual base method, not the overridden method.
What you are seeing is the polymorphic behaviour that is by design. When you override a virtual method, invoking that method on the overridden class calls the decendant class's implementation from the VMT.
What is your use case, to be honest this smells a little like a design problem.