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()

  

 

posted on   范兵  阅读(1090)  评论(0编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· 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与迭代器

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5
点击右上角即可分享
微信分享提示