反射一个类型中的成员,可得到如、、 或 等信息,这些对象从字面上看似乎很难发现有跟索引器对得上的.但是仔细分析索引器的本质,其实索引器是被归类为属性的,即可以通过
1
Type genericType = typeof(Dictionary<,>);2

3
Type dictionaryType = genericType.MakeGenericType(typeof(string), typeof(int));4
object dictonaryObj = Activator.CreateInstance(dictionaryType);5

6
MethodInfo method = dictionaryType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);7

method.Invoke(dictonaryObj, new object[]
{ "key", 1 });8

9
MethodInfo getValueMethod = dictionaryType.GetMethod("get_Item", BindingFlags.Instance | BindingFlags.Public);10

Console.WriteLine(getValueMethod.Invoke(dictonaryObj, new object[]
{ "key" }));












