c# - 发出属性以设置字典值
问题描述
我尝试为动态程序集中的属性发出设置字段方法。
想要的 C# 代码是:
private readonly Dictionary<string, object> propertyBag = new Dictionary<string, object>();
public string PropertyName
{
set { propertyBag["PropertyName"] = value; }
}
PropertyName 及其类型必须是动态的
我发出设置器的代码是:
PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName, PropertyAttributes.None, propertyType, Type.EmptyTypes);
FieldBuilder fieldBuilder = typeBuilder.DefineField("propertyBag", typeof(Dictionary<string, object>), FieldAttributes.Private);
MethodBuilder setMethodBuilder = typeBuilder.DefineMethod($"set_{propertyName}", MethodAttributes.Public | MethodAttributes.HideBySig, null, new[] { propertyType });
ILGenerator setIL = setMethodBuilder.GetILGenerator();
setIL.Emit(OpCodes.Ldarg_0);
setIL.Emit(OpCodes.Ldarg_1);
setIL.Emit(OpCodes.Ldfld, fieldBuilder);
setIL.Emit(OpCodes.Ldstr, propertyName);
setIL.Emit(OpCodes.Callvirt, fieldBuilder.FieldType.GetMethod("set_Item", new Type[] { typeof(string), typeof(object) }));
setIL.Emit(OpCodes.Ret);
propertyBuilder.SetSetMethod(setMethodBuilder);
运行设置属性的代码时,我有一个
AccessViolationException : 试图读取或写入受保护的内存。这通常表明其他内存已损坏。
一个主意?
解决方案
的参数顺序set_item
似乎是关闭的。
看看这个反编译的例子,value
(arg1) 应该是第二个参数,而不是第一个:
IL_0000: ldarg.0
IL_0001: ldfld class [System.Private.CoreLib]System.Collections.Generic.Dictionary`2<string, object> C::propertyBag
IL_0006: ldstr "PropertyName"
IL_000b: ldarg.1
IL_000c: callvirt instance void class [System.Private.CoreLib]System.Collections.Generic.Dictionary`2<string, object>::set_Item(!0, !1)
IL_0011: ret
取自这里: sharplab.io
推荐阅读
- typescript - 如何给出已经在@types/node 中声明的指定类型?
- c# - VS2017 Winfroms 无法更新服务参考
- google-chrome - material-ui:Chrome 意外自动填充
我试图阻止 Chrome 自动填充我的所有字段。我将 autocomplete='off' 添加到 TextField 和 Autocomplete 的输入中,如下所示:
<TextField autoComplete={'off'} <Autocomplete renderInput={par
- python - 如何做python顶级应用程序,但是当你打开一个新程序时,它会下降1级
- javascript - 如果存在于 mongodb 的数组中,则删除数组
- swift - 从循环中创建具有多个子元素的可编码结构
- python - 如何使用多线程来简化以下 python 代码
- c++ - 从 C++ 中的函数返回 this
- java - JAVA中的equals()方法
- laravel - Laravel Cashier 重用支付意图