我一直在尝试使用 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/