带有反射的 C# 字典/列表

标签 c# list reflection dictionary

大家好,我有一个字典类型的对象

我已经制作了一个函数,可以将数据添加到字典并使用反射从字典中获取数据。

我的问题是如何使用反射修改字典中的项目?

代码示例(不使用反射):

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/

相关文章:

c# - 我们是否需要安装 Office 才能使用 OpenXML?

excel - 将多个值存储到字典中

c# - 是否可以反编译整个 .NET 应用程序?

java - 从类名动态创建 java 对象,并使用带有数据的列表设置类字段

oracle - 有关 PL/SQL 包级记录类型的元数据

c# - FormClosing 关闭事件不写入文件

c# - 使用c#获取本地系统ip地址

c# - 使用 C# 显示消息后重定向页面

.net - 无法在 LINQ 中转换类型 'WhereSelectListIterator` 的对象

python - 如何在字典中的现有键中添加新值(而不丢失以前的值)?