views:

215

answers:

1

I'd like to create dynamically some method, which will accept single parameter - instance of class A and then will execute method B in passed instance of A. B has parameter of type int. So here is the schema:

dynamicMethod(A a){
a.B(12);
}

Here what I tried:

DynamicMethod method = new DynamicMethod(string.Empty, typeof(void), new[] { typeof(A) }, typeof(Program));
MethodInfo methodB = typeof(A).GetMethod("B", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { }, null);
ILGenerator gen = method.GetILGenerator();

gen.Emit(OpCodes.Nop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_S, 100);
gen.Emit(OpCodes.Call, methodB);

But compiler tells me that CLR doesn't found the method. Could you help me with it?

+1  A: 

MSDN about the types parameter of the Type.GetMethod function:

An array of Type objects representing the number, order, and type of the parameters for the method to get.

You pass an empty array which indicates "a method that takes no parameters". But as you said "B has [a] parameter of type int."

This will work:

MethodInfo methodB = typeof(A).GetMethod(
            "B",
            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
            null,
            new Type[] { typeof(int) }
            , null);


If I understand correctly Ldarg_S will load the one hundredth argument of your method, similiarly to Ldarg_0:

gen.Emit(OpCodes.Ldarg_S, 100);

For loading a constant value use Ldc_I4

gen.Emit(OpCodes.Ldc_I4, 100);
Yes, right, but how should I pass this parameter through Emit method? What OpCode should I use?
Paul Podlipensky