Identifying a custom indexer using reflection in C#

前端 未结 5 1159
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题