我在创建指令时尝试调用Nullable.Value时遇到问题。我正在做以下事情。
ModuleDefinition module = ModuleDefinition.ReadModule(@"C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll");
TypeReference boolean = module.GetType("System.Boolean", true);
TypeReference nullableBoolean = module.GetType("System.Nullable`1", true).MakeGenericInstanceType(boolean);
TypeDefinition typeDefinition = nullableBoolean.Resolve();
MethodDefinition get_HasValue = typeDefinition.Methods.Single(m => m.Name == "get_HasValue");
MethodDefinition get_Value = typeDefinition.Methods.Single(m => m.Name == "get_Value");
MethodReference methodReference = module.Import(get_Value);
processor.Create(OpCodes.Call, methodReference);
当我插入这些指令时,它会在ILSpy中查看以下内容,如果我尝试使用它运行代码,它会显示“InvalidProgramException:Invalid IL code”
call instance bool [mscorlib]System.Nullable`1::get_HasValue()
call instance !0 [mscorlib]System.Nullable`1::get_Value()
修改
经过一番捣乱,我能够更接近它应该是什么。来自Cecil的IL与来自编译生成代码的IL匹配,但现在我收到错误。我将包括我正在使用的代码以及我正在编辑的内容。Unhandled Exception: System.TypeLoadException: Could not load type 'System.Nullable' from assembly due to value type mismatch.
https://gist.github.com/7H3LaughingMan/311662c07b8bf8f8d2c6 https://gist.github.com/7H3LaughingMan/b606e99849f4d8addfc4 https://dl.dropboxusercontent.com/u/7231478/Test.exe