I'd like to make a delegate that invokes a specific instance method, unfortunately, it seems that if the method is virtual, the override of the method for the inheriting class will be invoked rather than the base version.
public class Base{
public virtual void Method(){
Console.WriteLine("Base");
}
}
public class Child : Base{
public override void Method(){
Console.WriteLine("Child");
}
}
If somewhere else in the code I have the following::
var action = Delegate.CreateDelegate(typeof(Action<Base>), typeof(Base).GetMethod("Method")) as Action<Base>;
action(new Child());
The output of this program is Child
. I'd really like it to be Base
. I've tried the same thing with expression trees and I get the same result, as the IL emitted uses the callvirt
method. Is the only way to do something like this really with Reflection.Emit
?
The reason I ask is that I am using a type builder to override behavior of a class. If I were to write the method myself, I could just go base.Method()
or whatever, but, some of the method behavior can only be determined dynamically at runtime, as accounting for the many possible cases would be very tedious.
Since i'm creating a class that derives from Base
at runtime, if I try to invoke Method()
inside the Method()
overload I'm making it leads to infinite recursion and stack overflow exceptions. (not so good).
This is for an AOP style project where I'm adding some logic to the methods at runtime. I tag the methods with attributes, I then have a type builder that create methodBuilders feeding the body of the methodbuilder with an expression tree using the CompileToMethod(methodbuilder)
http://msdn.microsoft.com/en-us/library/dd728224.aspx,
This is a ton easier than reflection.emit, as the logic is non-trivial that I am adding. The goal is than I have a factory spit out a new class that whenever I call Method()
it does some logic first before ultimately calling the base implementation.