How to get metadata custom attributes?

后端 未结 5 531
南方客
南方客 2021-01-05 08:23

I have a class that defines data annotations at class level. The meta data class has custom attributes associated with it, along with the usual DisplayName,

5条回答
  •  死守一世寂寞
    2021-01-05 08:43

    Have you tried just doing this,

    public class BaseViewModel
    {
        [DisplayName("Id")]
        public int Id { get; set; }
    
        [DisplayName("Selected")]
        [ExportItem(Exclude = true)]
        public bool Selected { get; set; }
    }
    

    You can then use a variation of your code,

    var type = typeof(T);    
    var propertyMetaData = type.GetProperties()
        .Select(property => 
            property.GetCustomAttributes(typeof(ExportItemAttribute), false)
                    .FirstOrDefault() as ExportItemAttribute)
        .Where(attribute => attribute == null || !attribute.Exclude)
        .ToList();
    

提交回复
热议问题