Identifying a custom indexer using reflection in C#

前端 未结 5 1144
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 16:42

I have a class with a custom indexer like so

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

How can I identify the custom index

相关标签:
5条回答
  • 2020-12-03 17:12

    If there is only one indexer, you can use this:

    var indexer = typeof(MyClass).GetProperties().First(x => x.GetIndexParameters().Length > 0));
    

    If there are multiple indexers, you can select the overload you want by supplying the arguments like this:

    var args = new[] { typeof(int) };
    var indexer = typeof(MyClass).GetProperties().First(x => x.GetIndexParameters().Select(y => y.ParameterType).SequenceEqual(args));
    

    You can create a helper extension like this:

    //Usage      
    var indexer = typeof(MyClass).GetIndexer(typeof(VehicleProperty));
    //Class
    public static class TypeExtensions
    {
      public static PropertyInfo GetIndexer(this Type type, params Type[] arguments) => type.GetProperties().First(x => x.GetIndexParameters().Select(y => y.ParameterType).SequenceEqual(arguments));
    }
    
    0 讨论(0)
  • 2020-12-03 17:15

    To get a known indexer you can use:

    var prop = typeof(MyClass).GetProperty("Item", new object[]{typeof(VehicleProperty)});
    var value = prop.GetValue(classInstance, new object[]{ theVehicle });
    

    or you can get the getter method of the indexer:

    var getterMethod = typeof(MyClass).GetMethod("get_Item", new object[]{typeof(VehicleProperty)});
    var value = getterMethod.Invoke(classInstance, new object[]{ theVehicle });
    

    if the class has only one indexer, you can omit the type:

    var prop = typeof(MyClass).GetProperty("Item", , BindingFlags.Public | BindingFlags.Instance);
    

    I've added this answer for the ones who google search led them here.

    0 讨论(0)
  • 2020-12-03 17:24

    Look for the DefaultMemberAttribute defined at type level.

    (This used to be IndexerNameAttribute, but they seem to have dropped it)

    0 讨论(0)
  • 2020-12-03 17:26
        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();
        }
    
    0 讨论(0)
  • 2020-12-03 17:30

    You can also look for index parameters, using the the PropertyInfo.GetIndexParameters method, if it returns more than 0 items, it's an indexed property:

    foreach (PropertyInfo pi in typeof(MyClass).GetProperties())
    {
        if (pi.GetIndexParameters().Length > 0)
        {
           // Indexed property...
        }
    }
    
    0 讨论(0)
提交回复
热议问题