在.NETCore中获取枚举值中文描述的方法详解
在.NETCore中,可通过自定义或内置DescriptionAttribute,结合反射编写GetDescription扩展方法,获取枚举值的中文描述。该方法支持单个枚举值获取及遍历所有枚举值返回描述字典,未定义时返回枚举名。
在 .NET 项目里,经常会遇到需要给枚举值配上中文描述的场景。比如下面这个 UserStatus 枚举,定义了几个状态,每个状态都对应一个中文说明:
public enum UserStatus
{
[Description("未激活")]
Inactive = 0,
[Description("已激活")]
Active = 1,
[Description("已禁用")]
Disabled = 2,
[Description("待审核")]
Pending = 3
}
那么问题来了——怎么在代码里拿到某个枚举值对应的中文描述呢?这事儿其实不复杂,几步就能搞定,而且有两种常见的实现方式,咱们挨个说。
1. 创建自定义特性
先定义一个自己的 DescriptionAttribute,用来存放中文描述信息。虽然 .NET 内置也有 DescriptionAttribute,但为了保持灵活性,这里先演示自定义的方式:
using System; ////// 枚举描述特性 /// public class DescriptionAttribute : Attribute { public string Description { get; } public DescriptionAttribute(string description) { Description = description; } }
2. 定义使用中文描述的枚举
把刚才定义的特性贴在枚举值上,就像文章开头展示的那样,这里就不再重复贴代码了。注意,如果你的项目已经引用了 System.ComponentModel,也可以直接用内置的 DescriptionAttribute,后面会讲到。
3. 创建扩展方法
关键步骤来了——写一个扩展方法,通过反射读取枚举字段上的 DescriptionAttribute,返回对应的描述文本。如果没找到任何特性,就回退到枚举名称本身,这样不至于报错。
using System;
using System.ComponentModel;
using System.Reflection;
public static class EnumExtensions
{
///
/// 获取枚举值的描述
///
public static string GetDescription(this Enum value)
{
if (value == null)
return string.Empty;
var field = value.GetType().GetField(value.ToString());
if (field == null)
return value.ToString();
// 尝试获取DescriptionAttribute
var attribute = field.GetCustomAttribute();
if (attribute != null)
return attribute.Description;
// 如果没有DescriptionAttribute,返回枚举名称
return value.ToString();
}
///
/// 获取枚举类型的所有值和描述(返回 int 键的字典)
///
public static Dictionary GetEnumDescriptions() where T : Enum
{
var result = new Dictionary();
var values = Enum.GetValues(typeof(T));
foreach (T value in values)
{
result.Add(Convert.ToInt32(value), value.GetDescription());
}
return result;
}
///
/// 获取枚举类型的所有值和描述(返回枚举键的字典)
///
public static Dictionary GetEnumDescriptionsDict() where T : Enum
{
return Enum.GetValues(typeof(T))
.Cast()
.ToDictionary(e => e, e => e.GetDescription());
}
}
4. 使用示例
代码写完了,验证一下效果。下面是一个简单的控制台示例,演示了三种常见用法:获取单个枚举值的描述、遍历所有枚举值、以及直接拿到字典:
Console.WriteLine("Hello, World!");
// 示例1:获取单个枚举值的描述
UserStatus status = UserStatus.Active;
string description = status.GetDescription();
Console.WriteLine($"状态描述: {description}"); // 输出: 状态描述: 已激活
// 示例2:遍历所有枚举值
foreach (UserStatus value in Enum.GetValues(typeof(UserStatus)))
{
Console.WriteLine($"{value}: {value.GetDescription()}");
}
// 示例3:获取所有枚举值的字典
var statusDict = EnumExtensions.GetEnumDescriptions();
foreach (var item in statusDict)
{
Console.WriteLine($"值: {item.Key}, 描述: {item.Value}");
}
Console.ReadKey();
打印结果如下,完全符合预期:
Hello, World!
状态描述: 已激活
Inactive: 未激活
Active: 已激活
Disabled: 已禁用
Pending: 待审核
值: 0, 描述: 未激活
值: 1, 描述: 已激活
值: 2, 描述: 已禁用
值: 3, 描述: 待审核
5. 替代方案:使用 System.ComponentModel.DescriptionAttribute
如果你不想自己定义特性,直接使用 .NET 内置的 System.ComponentModel.DescriptionAttribute 会更省事。用法完全一样,只需把引用从自定义特性换成内置的即可。注意枚举定义和扩展方法里的引用都要改过来:
using System.ComponentModel;
public enum UserStatus
{
[Description("未激活")]
Inactive = 0,
[Description("已激活")]
Active = 1
}
// 扩展方法中的引用也改为 System.ComponentModel.DescriptionAttribute
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
if (value == null)
return string.Empty;
var field = value.GetType().GetField(value.ToString());
if (field == null)
return value.ToString();
// 使用System.ComponentModel.DescriptionAttribute
var attribute = field.GetCustomAttribute();
if (attribute != null)
return attribute.Description;
return value.ToString();
}
}
两种方式核心逻辑一致,选哪种取决于你的项目风格和是否已经依赖了 System.ComponentModel。实际开发中,如果只是拿来做简单的枚举描述,直接内置的那个就够用了。
Postman是一套面向API全生命周期的开发与测试平台,可在Mac上发送和调试多种协议请求,管理集合、环境及认证信息,并完成脚本测试、模拟服务、监控、文档发布和团队协作。它适合开发、测试及运维人员使用,提供个人免费方案。
Docker Desktop 是 Docker 官方为 Mac 提供的容器开发环境,集成 Docker Engine、命令行工具、Compose、Build、Kubernetes 与图形化管理界面。
Android Studio 是 Google 面向安卓应用开发提供的官方集成开发环境,基于 IntelliJ IDEA 构建。它整合智能代码编辑、Gradle 构建、界面预览、设备模拟、性能分析、调试测试及 APK 分析等工具。
PixPix 是面向品牌、卖家和内容团队的在线 AI 图片视频创作平台,提供图视频 Agent、无限画布、图片生成、视频生成、自然语言编辑及商品套图、产品精修和带货视频等电商工具。
Postman 是面向 API 全生命周期的开发与协作平台。Windows 桌面版可用于构建和发送 HTTP、GraphQL、gRPC、WebSocket、MQTT 等请求,并提供环境变量、集合、脚本测试、模拟服务、监控、文档及团队工作区等
Docker Desktop 为 Windows 开发者提供集成式容器环境,内置 Docker Engine、命令行工具、Compose、Build 与 Kubernetes 等组件,可在本机完成镜像构建、容器运行、日志查看和资源管理。













