Reputation: 3189
I'm generating a new Type
via TypeBuilder
from C# reflection. The problem that I have right now is how to build method body to invoke method on static filed.
Right now my generated (at runtime) class looks like this:
public class Generated
{
static private MyObject obj;
public MyResponse Hello(MyRequest req1)
{
return obj.Hello(req1); // this part need to be grnerated
}
}
So right now I'm generating method like this:
MethodBuilder mb = tb.DefineMethod(
methodInfo.Name,
MethodAttributes.Public | MethodAttributes.Final,
CallingConventions.HasThis | CallingConventions.ExplicitThis,
methodInfo.ReturnType,
arguments);
ILGenerator il = mb.GetILGenerator();
il.Emit(OpCodes.Ldnull); // right now I'm just simply returning null
il.Emit(OpCodes.Ret);
So please tell me how can I load static field on stack in Il generator and then invoke certain method on it.
Upvotes: 0
Views: 251
Reputation: 3189
So I just used ildasm.exe
to decompile class that I've posted in my question. If anyone would need do staff similar to mine, below you have Il code:
IL_0000: nop
IL_0001: ldsfld class ConsoleApplication1.IMyInterface ConsoleApplication1.Controller::obj
IL_0006: ldarg.1
IL_0007: callvirt instance class ConsoleApplication1.MyResponse ConsoleApplication1.IMyInterface::Hello(class ConsoleApplication1.MyRequest)
IL_000c: stloc.0
IL_000d: br.s IL_000f
IL_000f: ldloc.0
IL_0010: ret
Also in my code I've removed lines IL_0000,c,d,f
, because (in my opinion) there are not needed.
Upvotes: 0