如何通过ILGenerator.Emit *调用'正常'方法?

时间:2011-05-06 04:43:23

标签: .net vb.net visual-studio-2010 dynamicmethod ilgenerator

DynamicMethod是否可以调用(通过ILGenerator.EmitCall - 或类似的 - 例如)'普通'方法,例如Private Sub BlahBlah(ByVal obj as Object)?

提前致谢

2 个答案:

答案 0 :(得分:4)

delegate void foo();

public static void show(string foo)
{
    MessageBox.Show(foo);
}

public void test()
{
    DynamicMethod dm = new DynamicMethod("foo", null, null);
    ILGenerator gen = dm.GetILGenerator();
    gen.Emit(OpCodes.Ldstr, "hello world");
    gen.EmitCall(OpCodes.Call, this.GetType().GetMethod("show"),null);
    gen.Emit(OpCodes.Ret);
    var b = dm.CreateDelegate(typeof(foo)) as foo;
    b();
}

答案 1 :(得分:4)

在评估堆栈上加载要赋予方法的值

MethodInfo methodInfo = typeof(ClassName).GetMethod(MethodName, new Type[1] { typeof(-method argument types-) });

IL.Emit(OpCodes.Call, methodInfo );