c#带反射的字典/列表
大家好,我有一个类型为dictionary的对象 我已经做了一个函数,可以将数据添加到字典中,并使用反射从字典中获取数据 我的问题是如何使用反射修改字典中的项 代码中的示例(不使用反射):c#带反射的字典/列表,c#,list,reflection,dictionary,C#,List,Reflection,Dictionary,大家好,我有一个类型为dictionary的对象 我已经做了一个函数,可以将数据添加到字典中,并使用反射从字典中获取数据 我的问题是如何使用反射修改字典中的项 代码中的示例(不使用反射): dictionary dict=new dictionary(); 添加(“键1”、“数据1”); dict.add(“键2”、“数据2”); console.writeline(dict[“key2”])/您需要找到所需的索引器属性,并通过该属性设置值: object key = // object new
dictionary dict=new dictionary();
添加(“键1”、“数据1”);
dict.add(“键2”、“数据2”);
console.writeline(dict[“key2”])/您需要找到所需的索引器属性,并通过该属性设置值:
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字典=新字典
{
{“1”,“john”},
{“2”,“玛丽”},
{“3”,“彼得”},
};
Console.WriteLine(字典[“1”]);//输出“约翰”
//这是索引器元数据;
//索引器属性以“项”命名
var prop=dictionary.GetType().GetProperty(“项”);
//第一个参数-字典实例,
//第二,新价值观
//第三个是具有单个项的索引器数组,
//因为Dictionary.Item[TKey]只接受一个参数
prop.SetValue(字典“James”,新[]{“1”});
Console.WriteLine(字典[“1”]);//输出“詹姆斯”
您是否有支持在编译时错误上突出显示语法的工具?请努力并展示至少可编译的代码。为什么必须使用反射?我需要使用反射,因为我在xml文件中列出了方法和变量,并且知道我要在xml文件中执行每个操作
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"