c# - 如何显示枚举显示属性的名称

标签 c# enums

<分区>

这是我的枚举。

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

希望这有帮助:)

关于c# - 如何显示枚举显示属性的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40995593/

相关文章:

c# - 如何获取字符串的一部分

c# - 如何为文本框设置数字 1000 到 1,000 的格式,以在标签和 message.show 中的 C# Tostring 中使用

c# - 实现插件/插件/插件策略的最佳实践

c# - ASP.NET Core 6 中的非缓冲输出

Delphi:如何拥有非连续子范围枚举类型?

Java - 枚举通配符

c++ - 枚举列表到 STL 容器

c# - CRL 无法通过 http 代理工作

postgresql - 如何为向上迁移添加枚举值的 Postgresql 编写向下迁移?

java - PostgreSQL 枚举和 Java 枚举之间的 hibernate 映射