反射调用索引器
反射一個類型中的成員,可得到如、、 或 等信息,這些對象從字面上看似乎很難發現有跟索引器對得上的.但是仔細分析索引器的本質,其實索引器是被歸類為屬性的,即可以通過
Code?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"?}));
轉載于:https://www.cnblogs.com/shenba/archive/2007/11/24/970919.html
總結
- 上一篇: 每次吸氧多长时间最佳?
- 下一篇: 用C++开发Web应用