当使用反射获取属性时,如何将搜索限制为我感兴趣的子类?

top*_*wik 5 reflection assemblies properties getproperties

在使用反射从程序集中成功获取特定类型的列表之后,我现在想要了解每个类型的公共属性.

这些类型中的每一种都源自至少一个基类.

我注意到当我获得一个类型的属性时,我也从基类中获取属性.

我需要一种方法来过滤掉基类属性,只返回我调用的类型属性的属性.

我认为它类似于我只从给定的基本类型获得基类型的子类,不包括基类型.

Assembly.GetAssembly(baseType).GetTypes().Where(type => type.IsSubclassOf(baseType)).ToList()
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 11

使用BindingFlags.DeclaredOnly在您的来电Type.GetProperties:

var properties = Type.GetProperties(BindingFlags.DeclaredOnly | 
                                    BindingFlags.Public |
                                    BindingFlags.Instance);
Run Code Online (Sandbox Code Playgroud)