【问题标题】:How to display the name of enum display attribute [duplicate]如何显示枚举显示属性的名称[重复]
【发布时间】:2017-04-21 02:32:12
【问题描述】:

这是我的枚举。

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

我看到有些解决方案包含大量代码。这没有简单/单行的解决方案吗?

请告诉我一个方向。

【问题讨论】:

标签: c# enums


【解决方案1】:

给定一个枚举

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

希望这会有所帮助:)

【讨论】:

  • enum 是关键字,不是有效的参数名称,设为@enum,这也将只返回第一个枚举值的显示名称,即“永久”,不管无论您使用ContractType.PartTime还是ContractType.Permanent
  • @ColinM:我猜你的评论不再正确了
猜你喜欢
  • 2015-04-24
  • 1970-01-01
  • 1970-01-01
  • 2021-08-06
  • 2017-04-14
  • 2011-09-08
  • 2011-07-11
  • 2016-01-18
  • 1970-01-01
相关资源
最近更新 更多