How to list interface methods omitting property accessors [duplicate]

喜夏-厌秋 提交于 2019-12-18 08:12:03

问题


I would like to use reflection to display a list of methods in an interface.

public interface IRoadVehicle
{
  int WheelCount { get; }
  bool IsEmergency();
}

I use following code:

foreach (var m in typeof(IRoadVehicle).GetMethods())
{
  Console.WriteLine(m.Name);
}

However, I also get listed the compiler-generated property accessors if the interface has a property. I would like to differentiate between explicitly-defined methods and property accessors to omit the latter.

//output:
//get_WheelCount
//IsEmergency

//desired output:
//IsEmergency

How can I filter out the property-related methods?


回答1:


You can use the IsSpecialName property:

foreach (var m in typeof(IRoadVehicle).GetMethods().Where(x => !x.IsSpecialName))
{
    // ...
}

This removes all methods with a name that is treated somehow special by the compiler. The docs say this about it:

The SpecialName bit is set to flag members that are treated in a special way by some compilers (such as property accessors and operator overloading methods).




回答2:


How about:

var type = typeof(IRoadVehicle);

var accessors = type.GetProperties().SelectMany(property => property.GetAccessors());
var methods = type.GetMethods()
                  .Except(accessors);

You can also use IsSpecialName like Daniel Hilgarth mentions, but note that this will also exclude other "special" methods like operators (not an issue for interfaces) and event-accessors. Depends on what you want, really.



来源:https://stackoverflow.com/questions/12216726/how-to-list-interface-methods-omitting-property-accessors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!