简体   繁体   English

从 PropertyInfo 获取 DisplayAttribute 属性

[英]Get DisplayAttribute attribute from PropertyInfo

class SomeModel
{
    [Display(Name = "Quantity Required")]
    public int Qty { get; set; }

    [Display(Name = "Cost per Item")]
    public int Cost { get; set; }
}

I'm trying to map the model into a list of { PropertyName, DisplayName } pairs, but I've got stuck.我试图将模型映射到{ PropertyName, DisplayName }对的列表中,但我被卡住了。

var properties 
    = typeof(SomeModel)
        .GetProperties()
        .Select(p => new 
            {
                p.Name,
                p.GetCustomAttributes(typeof(DisplayAttribute),
                              false).Single().ToString()
            }
        );

The above doesn't compile and I'm not sure it's the right approach anyway, but hopefully you can see the intent.以上内容无法编译,我不确定它是否是正确的方法,但希望您能看到意图。 Any pointers?任何指针? Thanks谢谢

In this case you need to define specific property names for anonymous type.在这种情况下,您需要为匿名类型定义特定的属性名称。

var properties = typeof(SomeModel).GetProperties()
    .Where(p => p.IsDefined(typeof(DisplayAttribute), false))
    .Select(p => new
        {
            PropertyName = p.Name,
            DisplayName = p.GetCustomAttributes(typeof(DisplayAttribute),
                false).Cast<DisplayAttribute>().Single().Name
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM