So I have a simple class reside in my assembly:
public class MyCalculator
{
public int Sum(params int[] nums)
{
Console.WriteLine("Summing");
return nums.Sum();
}
}
The first thing to know about is that the Sum method is not virtual. I don't want this limitation.
I want to 'override' the Sum
method to inject some code in runtime. (Just like any dynamic proxy framework do it. /for example: Castle/)
I created a dummy method (just the relevant parts):
MethodBuilder sumBuilder = myCalculatorProxyType.DefineMethod(myCalculatorSum.Name,
MethodAttributes.Public |
MethodAttributes.ReuseSlot |
MethodAttributes.HideBySig |
MethodAttributes.SpecialName |
MethodAttributes.Virtual |
MethodAttributes.Final,
CallingConventions.Standard,
myCalculatorSum.ReturnType,
myCalculatorSum.GetParameters().Select(pi => pi.ParameterType).ToArray());
In the end I try to "override" it with:
myCalculatorProxyType.DefineMethodOverride(sumBuilder,myCalculatorSum);
I play three possible option:
- The
MethodAttributes
- The CallingConventions
- And the
DefineMethodOverride
method
My concept: Make the method Public
obviously and HideBySig
. Additional ReuseSlot
in the vtable and called it with ExplicitThis
.
Any idea how to achieve this? Or need some more nasty thing?
I know there is frameworks outside, but I want to understand the concept of this.