C# .NET 获取枚举值的自定义属性
一、定义一个类
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace XXX.XXX.Utils { /// <summary> /// 备注特性 /// </summary> public class DescAttribute : Attribute { private string m_desc; public DescAttribute( string desc) { this .m_desc = desc; } /// <summary> /// 备注 /// </summary> public string Desc { get { return m_desc; } set { m_desc = value; } } /// <summary> /// 获取枚举的备注信息 /// </summary> /// <param name="val">枚举值</param> /// <returns></returns> public static string GetEnumDesc(Enum val) { Type type = val.GetType(); FieldInfo fd = type.GetField(val.ToString()); if (fd == null ) return string .Empty; object [] attrs = fd.GetCustomAttributes( typeof (DescAttribute), false ); string name = string .Empty; foreach (DescAttribute attr in attrs) { name = attr.Desc; } return name; } } /// <summary> /// 枚举扩展类 /// </summary> public static class EnumExtension { /// <summary> /// 获取枚举的备注信息 /// </summary> /// <param name="em"></param> /// <returns></returns> public static string GetDesc( this Enum em) { Type type = em.GetType(); FieldInfo fd = type.GetField(em.ToString()); if (fd == null ) return string .Empty; object [] attrs = fd.GetCustomAttributes( typeof (DescAttribute), false ); string name = string .Empty; foreach (DescAttribute attr in attrs) { name = attr.Desc; } return name; } } } |
二、定义一个枚举,并引用如上命名空间
1 2 3 4 5 | public enum EnumCalculationTag { [Desc( "This is description" )] A } |
三、获取注解(需引用“一”中的命名空间)
1 | EnumCalculationTag.A.GetDesc() |
分类:
C#,路上
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2014-01-24 [0] CollectionBase与索引符DictionaryBase与迭代器