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

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

Tôi đang cố gắng ánh xạ mô hình thành danh sách các cặp { PropertyName, DisplayName }, nhưng tôi đã bị kẹt.Nhận thuộc tính DisplayAttribute từ PropertyInfo

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

Ở trên không biên dịch và tôi không chắc đó là cách tiếp cận phù hợp, nhưng hy vọng bạn có thể thấy mục đích. Bất kỳ con trỏ? Cảm ơn

Trả lời

25

Bạn cần xác định các tên thuộc tính khác nhau cho loại ẩn danh.

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

Hoàn hảo, cảm ơn bạn – fearofawhackplanet

+0

@fearofawhackplanet, Bạn được chào đón! –