C#获取枚举描述的值

首先定义枚举

 工具类如下,通过扩展方法的方式实现:

复制代码
复制代码
public static string GetDescription(this Enum value)
        {
            Type enumType = value.GetType();
            // 获取枚举常数名称。
            string name = Enum.GetName(enumType, value);
            if (name != null)
            {
                // 获取枚举字段。
                FieldInfo fieldInfo = enumType.GetField(name);
                if (fieldInfo != null)
                {
                    // 获取描述的属性。
                    DescriptionAttribute attr = Attribute.GetCustomAttribute(fieldInfo,
                        typeof(DescriptionAttribute), false) as DescriptionAttribute;
                    if (attr != null)
                    {
                        return attr.Description;
                    }
                }
            }
            return null;
        }
复制代码
复制代码

使用:

 

 

 

出处:https://www.cnblogs.com/shenweif/p/16783500.html

posted on   jack_Meng  阅读(725)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
历史上的今天:
2022-06-08 树莓派修改分辨率
2021-06-08 bat中的退格符和延迟
2021-06-08 物联网网关开发:基于MQTT消息总线的设计过程
2021-06-08 物联网网关开发:进程之间通信方式--MQTT消息总线
2021-06-08 全图文分析:如何利用Google的protobuf,来思考、设计、实现自己的RPC框架
2020-06-08 免费下载 80多种的微软推出入门级 .NET视频
2015-06-08 使用bat文件实现批量重命名功能

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

支付宝打赏

主题色彩