使用C#中的reflection识别自定义索引器
我有一个类似自定义索引器的类
public string this[VehicleProperty property] { // Code }
如何在typeof(MyClass).GetProperties()的结果中识别自定义索引器?
您还可以使用PropertyInfo.GetIndexParameters方法查找索引参数,如果它返回的项目超过0,则它是一个索引属性:
foreach (PropertyInfo pi in typeof(MyClass).GetProperties()) { if (pi.GetIndexParameters().Length > 0) { // Indexed property... } }
查找在类型级别定义的DefaultMemberAttribute
。
(这曾经是IndexerNameAttribute
,但它们似乎已经删除了它)
static void Main(string[] args) { foreach (System.Reflection.PropertyInfo propertyInfo in typeof(System.Collections.ArrayList).GetProperties()) { System.Reflection.ParameterInfo[] parameterInfos = propertyInfo.GetIndexParameters(); // then is indexer property if (parameterInfos.Length > 0) { System.Console.WriteLine(propertyInfo.Name); } } System.Console.ReadKey(); }
要获得已知的索引器,您可以使用:
var prop = typeof(MyClass).GetProperty("Item", new object[]{typeof(VehicleProperty)}); var value = prop.GetValue(classInstance, new object[]{ theVehicle });
或者你可以得到索引器的getter方法:
var getterMethod = typeof(MyClass).GetMethod("get_Item", new object[]{typeof(VehicleProperty)}); var value = getterMethod.Invoke(classInstance, new object[]{ theVehicle });
如果类只有一个索引器,则可以省略类型:
var prop = typeof(MyClass).GetProperty("Item", , BindingFlags.Public | BindingFlags.Instance);
我已经为谷歌搜索带领他们的人添加了这个答案。