2011-09-07 107 views
17
class SomeModel 
{ 
    [Display(Name = "Quantity Required")] 
    public int Qty { get; set; } 

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

我试图将模型映射到{ PropertyName, DisplayName }对列表中,但我卡住了。从PropertyInfo获取DisplayAttribute属性

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

以上不编译,我不知道它是正确的方法,但希望你能看到意图。任何指针?谢谢

回答

25

您需要为匿名类型定义不同的属性名称。

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

完美,谢谢 – fearofawhackplanet

+0

@fearofawhackplanet,不客气! –