大家好,我有一个字典类型的对象
我已经制作了一个函数,可以将数据添加到字典并使用反射从字典中获取数据。
我的问题是如何使用反射修改字典中的项目?
代码示例(不使用反射):
dictionary<string, string> dict = new dictionary<string, string>();
dict.add("key1", "data1");
dict.add("key2", "data2");
console.writeline(dict["key2"]) // <- made using dynamic since it wont store to the objact data (made from relfection)
// code above already accomplished using reflection way
// code below, don't know how to accomplish using reflection way
dict["key2"] = "newdata" // <- how to modify the value of the selected item in object data (made from using reflection)
最佳答案
您需要找到所需的索引器属性并通过它设置值:
object key = //
object newValue = //
PropertyInfo indexProp = dict.GetType()
.GetProperties()
.First(p => p.GetIndexParameters().Length > 0 && p.GetIndexParameters()[0].ParameterType == key.GetType());
indexProp.SetValue(dict, newValue, new object[] { key });
如果你知道你正在处理一个通用字典,你可以直接获取属性,即
PropertyInfo indexProp = dict.GetType().GetProperty("Item");
关于带有反射的 C# 字典/列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16686612/