【问题标题】:Query Class Properties using Reflection with multiple conditions - Filter attributes使用具有多个条件的反射查询类属性 - 过滤属性
【发布时间】:2022-11-05 02:59:23
【问题描述】:

我想使用反射来查询类的公共属性
例如var properties = metaData.GetType().GetProperties()

接下来,我只想包含公共属性,因此它变为:

var properties = metaData.GetType().GetProperties().Where(x=>x.PropertyType.IsPublic)

接下来,我只想包含没有任何自定义属性的属性,或者如果它们确实有自定义属性,则它不能包含 AttributeType.Name 为“Computed”的属性

我想出了这个逻辑:

var properties = metaData.GetType().GetProperties().Where(x=>x.PropertyType.IsPublic && (!x.CustomAttributes.Any() || x.CustomAttributes.Where(y=>y.AttributeType.Name!="Computed").Any()));

这是最好的方法还是有另一种方法来编写这个 linq 查询?

【问题讨论】:

    标签: c# linq reflection attributes


    【解决方案1】:

    下面给出的ComputedAttributeMetaData 类或多或少符合您的设置。

    [AttributeUsage(AttributeTargets.All)]
    public sealed class ComputedAttribute : Attribute
    { }
    
    public class MetaData
    {
        public string RegularProperty { get; set; }
    
        [Computed]
        public string ComputeProperty { get; set; }
    }
    

    您可以使用下面的 LINQ 查询来仅检索未应用 Computed 属性的公共属性。

    GetCustomAttribute<T> 处理属性过滤。

       using System.Reflection;       
    
        var metaData = new MetaData();
        var props = metaData.GetType().GetProperties()
            .Where(x => 
                x.PropertyType.IsPublic // or IsVisble
                && x.GetCustomAttribute<ComputedAttribute>() == null
            );
    

    【讨论】:

      猜你喜欢
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多