gpt4 book ai didi

c# - 为什么我得到异常 : Common Language Runtime detected an invalid program

转载 作者:行者123 更新时间:2023-11-30 20:48:20 24 4
gpt4 key购买 nike

我正在使用 Mono cecil 自动实现 propertychanged 接口(interface)。一切正常,直到今天我得到异常公共(public)语言运行时检测到一个无效程序。我的单声道 C# 代码是:

ILProcessor MSILWorker = prop.SetMethod.Body.GetILProcessor();
MSILWorker.Body.InitLocals = true;
MSILWorker.InsertBefore(MSILWorker.Body.Instructions[0], MSILWorker.Create(OpCodes.Nop));
MSILWorker.InsertBefore(MSILWorker.Body.Instructions[1], MSILWorker.Create(OpCodes.Ldarg_0));
Instruction propertyName = MSILWorker.Create(OpCodes.Ldflda, field);
MSILWorker.InsertBefore(MSILWorker.Body.Instructions[3], propertyName);
MSILWorker.InsertAfter(MSILWorker.Body.Instructions[4], MSILWorker.Create(OpCodes.Ldstr, prop.Name));
Instruction callRaisePropertyChanged = MSILWorker.Create(OpCodes.Call, method_reference);
MSILWorker.Replace(MSILWorker.Body.Instructions[6], callRaisePropertyChanged);
MSILWorker.InsertBefore(MSILWorker.Body.Instructions.Last(), MSILWorker.Create(OpCodes.Pop));

生成的il代码是:

.method public hidebysig newslot specialname virtual final 
instance void set_CreateDate(valuetype [mscorlib]System.DateTime 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 21 (0x15)
.maxstack 4
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.0
IL_0003: ldflda valuetype [mscorlib]System.DateTime Framework.Data.Base.BaseEntity::'<CreateDate>k__BackingField'
IL_0008: ldarg.1
IL_0009: ldstr "CreateDate"
IL_000e: call instance void Framework.Data.Base.BaseEntity::SetField<valuetype [mscorlib]System.DateTime>(!!0&,
!!0,
string)
IL_0013: pop
IL_0014: ret
} // end of method BaseEntity::set_CreateDate

我尝试与用 C# 为另一个字段编写的属性进行比较,具有完全相同的逻辑,生成的 IL 代码是:

.method public hidebysig newslot specialname virtual final 
instance void set_LastModifiedDate(valuetype [mscorlib]System.DateTime 'value') cil managed
{
// Code size 21 (0x15)
.maxstack 8
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldarg.0
IL_0003: ldflda valuetype [mscorlib]System.DateTime Framework.Data.Base.BaseEntity::_LastModifiedDate
IL_0008: ldarg.1
IL_0009: ldstr "LastModifiedDate"
IL_000e: call instance void Framework.Data.Base.BaseEntity::SetField<valuetype [mscorlib]System.DateTime>(!!0&,
!!0,
string)
IL_0013: nop
IL_0014: ret
} // end of method BaseEntity::set_LastModifiedDate

有人可以帮助我吗?我做错了什么?

谢谢

最佳答案

您的堆栈不平衡。 C# 生成的示例在 IL_0013 处有一个 nop,您有一个 pop

我的猜测是您正在调用 void 方法,因此不需要丢弃结果。

删除 MSILWorker.InsertBefore(MSILWorker.Body.Instructions.Last(), MSILWorker.Create(OpCodes.Pop));

关于c# - 为什么我得到异常 : Common Language Runtime detected an invalid program,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24740362/

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