这是我的枚举。
public enum ContractType
{
[Display(Name = "Permanent")]
Permanent= 1,
[Display(Name = "Part Time")]
PartTime= 2,
}
我尝试使用下面的代码获取显示名称。
string x = Enum.GetName(typeof(ContractType), 2);
但它是返回" PartTime "总是。其实我想得到display属性的名称。 对于上面的示例,x应分配兼职
我看到有大量代码的解决方案。这不是一个简单的/一线解决方案吗?
请告诉我一个方向。
答案 0 :(得分:9)
给出一个枚举
Where
获取数据注释显示名称的自定义方法。
public enum ContractType
{
[Display(Name = "Permanent")]
Permanent= 1,
[Display(Name = "Part Time")]
PartTime //Automatically 2 you dont need to specify
}
调用GetDisplayName()
//This is a extension class of enum
public static string GetEnumDisplayName(this Enum enumType)
{
return enumType.GetType().GetMember(enumType.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.Name;
}
希望这会有所帮助:)