c# - 如何获取枚举显示名称

标签 c#

我定义了一个 emun,如下面的示例所示。

 public enum SampleEnum : int
{
    [Display(Name = "One")]
    Test_One = 1,
    [Display(Name = "Two")]
    Test_Two = 2,
    [Display(Name = "Three")]
    Test_Three = 3

}

在下面的代码行中,如何获取显示而不是名称?

   var displayName = Enum.GetName(typeof(SampleEnum ), 2); 

在上面的行中,我想得到 Two 而不是 Test_Two

最佳答案

您可以为其创建扩展方法。

   public static class EnumExtensions
      {
        public static string GetDisplayName(this Enum enumValue)
        {
          return enumValue.GetType()
            .GetMember(enumValue.ToString())
            .First()
            .GetCustomAttribute<DisplayAttribute>()
            ?.GetName();
        }
      }

https://dnilvincent.com/blog/posts/how-to-get-enum-display-name-in-csharp-net

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

相关文章:

c# - 如何动态列出和访问 TabPage 对象

c# - 谷歌翻译 C#

c# - 使用 Google Drive Api v2 选择特定字段

C# pinvoke 具有 union 和数组的结构

c# - Windows 身份验证并通过数据库添加授权角色 - MVC asp.net

c# - 在 Windows 上使用 Xamarin 进行 iOS UI 测试

c# - 使用 SqlDataAdapter 更新数据库 View

c# - 操作实体的类的名称

c# - 找出哪个类调用了一个方法

c# - 将字节交换/移位代码片段从 C++ 转换为 .NET