2

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
  • 1
    You can consider using System.Linq.Expressions to compile an expression tree instead. It's easier. Commented Sep 6, 2009 at 3:09

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, right, but how should I pass this parameter through Emit method? What OpCode should I use?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.