如何显示枚举显示名称 [英] How to display the name of enum display attribute

查看:115
本文介绍了如何显示枚举显示名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的枚举。

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

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

}

我尝试使用以下代码获取显示名称。

I try to get display name using below code.

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

但始终返回 PartTime 。实际上,我想获取显示属性的名称。
对于上面的示例,应该为x分配兼职

But it is return "PartTime" always. Actually I want to get the name of display attribute. For above example x should be assigned Part Time

我看到有些解决方案具有大量代码。这不是一个简单的单行解决方案吗?

I saw there are solutions which having huge code. Doesn't this have a simple/one line solution?

请告诉我一个方向。

推荐答案

给出一个枚举

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

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

用于获取数据注释显示名称的自定义方法。

Custom method to get the data annotation display name.

//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()

Calling GetDisplayName()

ContractType.Permanent.GetEnumDisplayName();

希望这会有所帮助:)

这篇关于如何显示枚举显示名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆