2009-08-28 21 views
27

使用反射的自定義索引我有一個類具有自定義索引像這樣蔡作馨在C#

public string this[VehicleProperty property] 
{ 
    // Code 
} 

我怎麼能確定typeof運算的結果(MyClass的).GetProperties()自定義索引?

回答

38

你也可以尋找指標參數,使用該PropertyInfo.GetIndexParameters方法,如果返回大於0的項目,這是一個索引屬性:

foreach (PropertyInfo pi in typeof(MyClass).GetProperties()) 
{ 
    if (pi.GetIndexParameters().Length > 0) 
    { 
     // Indexed property... 
    } 
} 
+0

打我+1(我還在打字) – MaLio 2009-08-28 16:18:40

4

查找在類型級別定義的DefaultMemberAttribute

(這曾經是IndexerNameAttribute,但他們似乎已經放棄了它)

+0

的'DefaultMemberAttribute'不必要的參考索引器,請參閱本[答案](https://stackoverflow.com/a/1119949/1161635)。 – Herman 2017-12-19 10:44:44

3
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(); 
    }