2013-05-22 84 views
2

嗨說我有一個對象類型的字典C#字典/列表與反思

我已經提出,將數據添加到字典和使用反射從字典中獲得數據的功能。

我的問題是如何修改字典中使用反射的項目?在碼(不使用反射)

例子:

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) 
+0

您是否有[IDE](http://en.wikipedia.org/wiki/Integrated_development_environment)支持編譯時錯誤的語法高亮顯示?請付出努力並顯示至少編譯的代碼。 –

+0

爲什麼你必須使用反射? –

+0

我需要使用反射,因爲我列出了xml文件中的方法和變量,並且知道我想要在xml文件中執行每個動作 – user2381378

回答

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