这是我的枚举。
public enum ContractType
{
[Display(Name = "Permanent")]
Permanent= 1,
[Display(Name = "Part Time")]
PartTime= 2,
}
我尝试使用以下代码获取显示名称。
string x = Enum.GetName(typeof(ContractType), 2);
但它总是返回“PartTime”。其实我想得到显示属性的名称。
对于上面的例子 x 应该被分配 Part Time
我看到有些解决方案的代码量很大。这不是有一个简单的/一行解决方案吗?
请告诉我一个方向。
给定一个枚举
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();
希望这有帮助:)