Normally, when I want to call a dynamic method in another ILGenerator object that is writing a method on the same type I do the following :
generator.Emit(OpCodes.Ldarg_0); // reference to the current object
gen开发者_运维知识库erator.Emit(OpCodes.Ldstr, "someArgument");
generator.Emit(OpCodes.Call, methodBuilder); //this methodbuilder is also defined on this dynamic type.
However, I faced the following problem: I cant have a reference to the methodbuilder of the method I want to call, because it is generated by another framework(I only get a reference to the current TypeBuilder). This method is defined as protected virtual(and overriden on the methodbuilder I cant get a reference to) in the base class of the current dynamic type and I can get a reference to it by doing this :
generator.Emit(OpCodes.Ldarg_0); // reference to the current object
generator.Emit(OpCodes.Ldstr, "someArgument");
generator.Emit(OpCodes.Call, baseType.GetMethod("SomeMethodDefinedInBaseClassThatWasOverridenInThisDynamicType"));
The problem is that this calls the method on the base type and not the overriden method.
Is there any way I can get a reference to a methodbuilder only having a reference to the typebuilder that defined it? Or is there a way to call a method using ILGenerator without having to pass the 'MethodInfo' object to it?
Not sure I follow, but you need to use Opcodes.CallVirt to call virtual methods. Which should automatically invoke the overridden method.
精彩评论