【问题标题】:C#, filter custom attribute property valuesC#,过滤自定义属性属性值
【发布时间】:2020-12-19 22:24:45
【问题描述】:

考虑一个类:

    public class Dog
    {
        [Key]
        [TableField(Name= "Jersey", Inoculated = false)]
        public string Param1{ get; set; }

        [TableField(Name= "Daisy", Inoculated = true)]
        public string Param2{ get; set; }

        [TableField(Name= "Jeremy", Inoculated = true)]
        public string Param3{ get; set; }
    }

还有一个属性类:

    public sealed class TableField : Attribute
    {
        public string Name { get; set; }
        public bool Inoculated { get; set; }
    }

这与现实生活中的例子有点远,但我需要从 typeof(Dog) (默认类值)中选择所有 TableField.Name 属性值,其中 TableField.Inoculated == true。

最佳尝试,不知道从哪里开始:

var names = typeof(Dog).GetProperties()
    .Where(r => r.GetCustomAttributes(typeof(TableField), false).Cast<TableField>()
    .Any(x => x.Inoculated));

【问题讨论】:

  • 您要的是IEnumerable&lt;T&gt; 还是IQueriable&lt;T&gt;

标签: c# linq attributes filtering


【解决方案1】:

如果您需要按属性从属性中进行选择,以下示例可能对您有用。

var dogType = typeof(Dog);
var names = dogType.GetProperties()
                .Where(x => Attribute.IsDefined(x, typeof(TableField)))
                .Select(x => x.GetCustomAttribute<TableField>())
                .Where(x => x.Inoculated == true)
                .Select(x=>x.Name);

【讨论】:

    【解决方案2】:

    通过使用 System.Reflection,您可以执行以下操作:

        public static Dictionary<string, string> GetDogNames()
        {
            var namesDict = new Dictionary<string, string>();
    
            var props = typeof(Dog).GetProperties();
            foreach (PropertyInfo prop in props)
            {
                object[] attrs = prop.GetCustomAttributes(true);
                foreach (object attr in attrs)
                {
                    if (attr is TableField tableField && tableField.Inoculated)
                    {
                        string propName = prop.Name;
                        string auth = tableField.Name;
    
                        namesDict.Add(propName, auth);
                    }
                }
            }
    
            return namesDict;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-08
      • 2012-02-15
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      相关资源
      最近更新 更多