【问题标题】:c# dictionary/list with reflection时间:2019-03-01 标签:c#dictionary/list with reflection
【发布时间】:2013-05-22 08:08:40
【问题描述】:

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

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

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

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

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)

【问题讨论】:

  • 你有一个IDE 支持编译时错误的语法高亮吗?请努力并显示至少可以编译的代码。
  • 为什么必须使用反射?
  • 我需要使用反射,因为我在 xml 文件中列出了方法和变量,并且知道我想执行 xml 文件中的每个操作

标签: c# list reflection dictionary


【解决方案1】:

您需要找到您需要的索引器属性并通过它设置值:

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

【讨论】:

    【解决方案2】:
            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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      • 2019-01-09
      • 1970-01-01
      相关资源
      最近更新 更多