c# - IL 通过字符串调用方法

标签 c# reflection.emit

我一直在尝试使用 IL Reflection 为 CIL 创建自己的玩具编程语言来生成 exe,但是当我调用方法时,我似乎不起作用。

我正在使用System.Reflection.ILGenerator.Emit(OpCodes.Call, MethodInfo)

当从使用 typeof(something) 获取的 Type 获取 MethodInfo 时,它工作正常,调用通过并且它可以工作,但是当我使用 Type.GetType(string) 函数获取 Type 时,由于某种原因它不会生成 IL,我已经测试并发现typeof == Type.GetType(使用 == 运算符检查时结果没有差异)。

我环顾四周,但似乎找不到任何解决方案,谁能告诉我发生了什么事?

编辑: here is a link to the git repo file

代码:

//Create IL Generator and standard stuff before this...
ilGenerator.Emit(OpCodes.Ldstr, "hello world"); //Push argument(s)
MethodInfo method = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
MethodInfo rmethod = Type.GetType("System.Console").GetMethod("WriteLine", new Type[] { typeof(string) });
if(method == rmethod)
{
    Console.WriteLine("MATCH!"); //This fires so I know they match
}
ilGenerator.Emit(OpCodes.Call, method); //This works
ilGenerator.Emit(OpCodes.Call, rmethod); //This does not... (no exceptions, but no code is generated looking with ILSpy afterwards)

最佳答案

我发现了问题,在执行之前的代码中的某个时刻, typebuilder.CreateType 被触发,这会停止 il 生成...

感谢您的帮助!

关于c# - IL 通过字符串调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20346442/

相关文章:

c# - 如何将 Expression.Lambda 附加到任何所有者类型?

cil - 在 VB.Net 中使用 System.Reflection.Emit.ILGenerator 调用 Random?

c# - 将sql查询命令超时设置为max的负面影响

c# - 在 C# 中以编程方式终止 vista/windows 7 中的进程

c# - RabbitMQ c# System.IO.EndOfStreamException 异常

c# - IL 无效程序,不明白为什么

c# - Reflection.Emit 的性能损失

c# - 使用 VC++ MFC 对话从数据库中检索数据

c# - 从 Exception.Data c# 中按键获取值

c# - 使用引用其依赖项的构造函数创建动态类型