簡體   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