简体   繁体   English

C#字典/反射列表

[英]c# dictionary/list with reflection

HI guys say I have an object with type dictionary 嗨,大家好,我有一个带有字典类型的物体

I already made a function that will add data to dictionary and get data from a dictionary using reflection. 我已经制作了一个函数,该函数将向字典添加数据并使用反射从字典中获取数据。

My problem is how do you modify an item in dictionary using reflection? 我的问题是如何使用反射修改字典中的项目?

Example in code (not using reflection): 代码示例(不使用反射):

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)

You need to find the indexer property you need and set the value through that: 您需要找到所需的索引器属性,并通过该属性设置值:

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 });

If you know you're dealing with a generic dictionary, you can get the property directly ie 如果您知道要处理通用词典,则可以直接获取该属性,即

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM