反射一个类型中的成员,可得到如MemberInfo、MethodInfo、FieldInfo 或 PropertyInfo 等信息,这些对象从字面上看似乎很难发现有跟索引器对得上的.但是仔细分析索引器的本质,其实索引器是被归类为属性的,即可以通过PropertyInfo获取对索引器的调用.而访问属性又是通过get,set方法获取的,索引器其实也有它自己的get,set方法.在类中定义的索引器,程序编译之后最终生成的IL中就包含了一对默认的get_Item(), set_Item()方法,对应的索引器属性为Item.这样分析之后,我们就可以通过MethodInfo来操作索引器.另外生成的get_Item(), set_Item()方法名称,并不是不能改的.可以通过设置索引器属性[IndexerName("MyIndex")],这样生成的索引器的方法对应的就是get_MyIndex(), set_MyIndex().
![](/Images/OutliningIndicators/ContractedBlock.gif)
Code
1
Type genericType = typeof(Dictionary<,>);
2![](/Images/OutliningIndicators/None.gif)
3
Type dictionaryType = genericType.MakeGenericType(typeof(string), typeof(int));
4
object dictonaryObj = Activator.CreateInstance(dictionaryType);
5![](/Images/OutliningIndicators/None.gif)
6
MethodInfo method = dictionaryType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance);
7![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
method.Invoke(dictonaryObj, new object[]
{ "key", 1 });
8![](/Images/OutliningIndicators/None.gif)
9
MethodInfo getValueMethod = dictionaryType.GetMethod("get_Item", BindingFlags.Instance | BindingFlags.Public);
10![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
Console.WriteLine(getValueMethod.Invoke(dictonaryObj, new object[]
{ "key" }));