使用反射来识别具有给定装饰器的属性

Pau*_*els 2 .net c# sqlite reflection properties

我正在尝试获取类中的属性列表,其中属性用装饰器 [Ignore] (SQLite.Net) 标记,尽管我相信该问题适用于任何装饰器。

var ignored = typeof(T)
            .GetType()
            .GetProperties().Where(p =>
                p.GetCustomAttributes<SQLite.Net.Attributes.IgnoreAttribute>())
            .ToList();
Run Code Online (Sandbox Code Playgroud)

我已经尝试了各种组合——这里的组合甚至不能编译,但访问 p.CustomAttributes 集合可以;但是,它不会返回正确的属性。为了完整起见,这里是 T 中的属性:

private ProductCategory _category;

[Ignore]
public ProductCategory Category
{
    get { return _category; }
    set
...
Run Code Online (Sandbox Code Playgroud)

请有人在这里指出我正确的方向 - CustomAttributes 甚至是寻找这个的正确位置吗?

Dan*_*rts 5

您的代码示例有两个主要问题 -

首先,typeof(T) 返回一个类型,因此您不需要对其调用 GetType()(这样做会返回有关Type类的信息,而不是有关“T”的返回信息)。

第二个问题是你不能在 Where lambda 中只调用“p.GetCustomAttributes(whatever)”,因为这不会导致布尔结果,你需要调用“p.GetCustomAttributes(whatever).Any()” .

由于 GetCustomAttributes 调用中的泛型类型参数,您的代码也没有在我的计算机上编译。但我确定我过去已经这样做了!也许我正在使用不同版本的框架或其他东西。

对我有用的代码如下:

var ignored = typeof(T)
    .GetProperties()
    .Where(p => p.GetCustomAttributes(typeof(IgnoreAttribute), inherit: true).Any())
    .ToList();
Run Code Online (Sandbox Code Playgroud)

(您是否需要“继承:真实”取决于您的对象模型,但我怀疑它在大多数情况下是合适的)。