18
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()
            }
        );

上面没有编译,我不确定它是否是正确的方法,但希望你能看到意图。任何指针?谢谢

4

1 回答 1

33

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

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
        });
于 2011-09-07T14:40:03.900 回答