Identifying a custom indexer using reflection in C#

前端 未结 5 1166
隐瞒了意图╮
隐瞒了意图╮ 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));
    }
    

提交回复
热议问题