gpt4 book ai didi

c# - 从 MethodInfo 生成 DynamicMethod

转载 作者:行者123 更新时间:2023-11-30 22:45:21 29 4
gpt4 key购买 nike

我正在查看 Joel Pobar 的 Dodge Common Performance Pitfalls to Craft Speedy Applications关于反射的文章,我正在查看一段未编译的特定代码(稍微修改以缩小到特定错误,因为他的示例有更多错误):

MethodInfo writeLine = typeof(Console).GetMethod("WriteLine");
RuntimeMethodHandle myMethodHandle = writeLine.MethodHandle;
DynamicMethod dm = new DynamicMethod(
"HelloWorld", // name of the method
typeof(void), // return type of the method
new Type[]{}, // argument types for the method
false); // skip JIT visibility checks

ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Ldstr, "Hello, world");
il.Emit(OpCodes.Call, myMethodHandle); // <-- 2 errors here
il.Emit(OpCodes.Ret);

错误是:

Program.cs(350,13): error CS1502: The best overloaded method match for 'System.Reflection.Emit.ILGenerator.Emit(System.Reflection.Emit.OpCode, byte)' has some invalid arguments
Program.cs(350,35): error CS1503: Argument '2': cannot convert from 'System.RuntimeMethodHandle' to 'byte'

ILGenerator 可以使用 MethodInfo Emit,但它似乎不支持 MethodHandle.. . 有没有人知道如何让这个示例工作?

最佳答案

像这样吗?

        MethodInfo writeLine = typeof(Console).GetMethod("WriteLine", new Type[] {typeof(string)});
RuntimeMethodHandle myMethodHandle = writeLine.MethodHandle;
DynamicMethod dm = new DynamicMethod(
"HelloWorld", // name of the method
typeof(void), // return type of the method
new Type[] { }, // argument types for the method
false); // skip JIT visibility checks

ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Ldstr, "Hello, world");
il.EmitCall(OpCodes.Call, writeLine, null);
il.Emit(OpCodes.Ret);
// test it
Action act = (Action)dm.CreateDelegate(typeof(Action));
act();

变化:

  • 我使用经过调整的 GetMethod 来查找 (string) 重载(否则它是不明确的匹配)
  • 使用MethodInfo,而不是句柄(因为那是ILGenerator 想要的)
  • 使用 EmitCall(另一个可能也有效,但我知道这种方法有效)

关于c# - 从 MethodInfo 生成 DynamicMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3104404/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com