C#,过滤自定义属性属性值

时间:2020-08-31 19:22:13

标签: c# linq attributes filtering

考虑一个课程:

    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));

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

通过使用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;
    }