【问题标题】:Using reflection to identify properties with a given decorator使用反射来识别具有给定装饰器的属性
【发布时间】:2016-12-22 00:06:57
【问题描述】:

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

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

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

private ProductCategory _category;

[Ignore]
public ProductCategory Category
{
    get { return _category; }
    set
...

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

【问题讨论】:

    标签: c# .net sqlite reflection properties


    【解决方案1】:

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

    首先,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();
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-20
      • 2013-04-10
      • 2014-02-14
      • 2018-08-16
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多