2016-12-06 177 views
3

這是我的枚舉。如何顯示枚舉顯示屬性的名稱

public enum ContractType 
{ 
    [Display(Name = "Permanent")] 
    Permanent= 1, 

    [Display(Name = "Part Time")] 
    PartTime= 2, 

} 

我嘗試使用下面的代碼獲取顯示名稱。

string x = Enum.GetName(typeof(ContractType), 2); 

但它的回報 「兼職」 始終。其實我想獲得顯示屬性的名稱。 對於上面的例子x應該被分配兼職

我看到有解決方案,有巨大的代碼。這是不是有一個簡單的/單線解決方案?

請給我看一個方向。

+5

http://stackoverflow.com/questions/13099834/how-to-get-the-display-name-枚舉成員通過mvc剃刀代碼的屬性 – Valentin

回答

8

給定一個枚舉

public enum ContractType 
{ 
    [Display(Name = "Permanent")] 
    Permanent= 1, 

    [Display(Name = "Part Time")] 
    PartTime //Automatically 2 you dont need to specify 
} 

自定義方法來獲取數據的註釋顯示名稱。

//This is a extension class of enum 
public static string GetEnumDisplayName(this Enum enumType) 
{ 
    return enumType.GetType().GetMember(enumType.ToString()) 
        .First() 
        .GetCustomAttribute<DisplayAttribute>() 
        .Name; 
} 

調用GetDisplayName()

ContractType.Permanent.GetEnumDisplayName(); 

希望這有助於:)

+1

enum是一個關鍵字,不是一個有效的參數名稱,使它成爲@ enum,這也將返回僅用於第一個枚舉值是「永久」,無論您是使用「ContractType.PartTime」還是「ContractType.Permanent」 – ColinM