返回
c#获取枚举的Description
2023-04-14 3943 0
要获取 C# 中枚举的描述(Description),可以使用反射和自定义属性来实现。
首先,需要在枚举值上定义自定义属性(Custom Attribute),用于存储描述信息。例如:
public enum MyEnum
{
[Description("This is the first value")]
Value1,
[Description("This is the second value")]
Value2,
[Description("This is the third value")]
Value3
}
接下来,可以编写一个扩展方法来获取枚举值的描述。例如:
using System;
using System.ComponentModel;
using System.Reflection;
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute
= Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))
as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
}
现在,可以使用该扩展方法获取枚举值的描述。例如:
MyEnum myValue = MyEnum.Value1;
string description = myValue.GetDescription();
Console.WriteLine(description); // 输出:This is the first value
注意,上述方法中使用了 System.ComponentModel 命名空间中的 DescriptionAttribute 类来定义自定义属性。如果在项目中没有使用该命名空间,则需要添加对 System.ComponentModel 命名空间的引用。
网友点评
提交
相关阅读
.NET C#创业适合做什么项目?
c# int数值转enum枚举
C# dynamic推断类型变量的性能和使用方法
C# Dictionary字典高级用法
C#正则表达式去除网页标签的id class style
基于C#开发的socket扩展库SuperSocket用法
c#使用HtmlAgilityPack编辑html并保存
c# 遍历list哪个方式性能最高
相关帖子
全球主流搜索引擎站长平台入口与网站提交全指南
Windscribe加速器深度评测:免费/付费版全方位剖析与使用建议
2025年最有潜力的百倍币:值得关注的加密货币项目
freewhale自由鲸不能用了?freewhale自由鲸跑路了? - 推荐完美替代 DOVE 加速器
DOVE加速器好用吗?2025最佳外网加速器推荐指南
OpenClaw AI Agent 是否被过度吹捧?普通人真的需要养龙虾吗?
wallless机场怎么样?wallless官网打不开,不能用了?wallless机场跑路了?推荐替代 – DOVE加速器
TLY不能用了?跑路了?TLY和beecloud机场代理完美替代 - DOVE加速器 评测