繁体   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; }
}

我试图将模型映射到{ PropertyName, DisplayName }对的列表中,但我被卡住了。

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

以上内容无法编译,我不确定它是否是正确的方法,但希望您能看到意图。 任何指针? 谢谢

在这种情况下,您需要为匿名类型定义特定的属性名称。

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