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

本文关键字:列表 字典 反射的 | 更新日期: 2023-09-27 18:14:42

嗨,伙计们,我有一个类型为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)

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

您需要找到所需的indexer属性并通过该属性设置值:

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");
        var dictionary = new Dictionary<string, string>
        {
            { "1", "Jonh" },
            { "2", "Mary" },
            { "3", "Peter" },
        };
        Console.WriteLine(dictionary["1"]); // outputs "John"
        // this is the indexer metadata;
        // indexer properties are named with the "Item"
        var prop = dictionary.GetType().GetProperty("Item");
        // the 1st argument - dictionary instance,
        // the second - new value
        // the third - array of indexers with single item, 
        // because Dictionary<TKey, TValue>.Item[TKey] accepts only one parameter
        prop.SetValue(dictionary, "James", new[] { "1" });
        Console.WriteLine(dictionary["1"]); // outputs "James"