如何列出接口方法忽略属性访问器属性、接口、方法

2023-09-03 05:14:57 作者:不負歲月不負伱

我想使用反射来显示接口的方法列表。

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

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

我用下面的code:

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?

推荐答案

您可以使用IsSpecialName属性:

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:

的SpecialName位被设置到由一些编译器处理以特殊方式标记部件(如属性访问和操作重载方法)。

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).