C# 获取枚举值描述信息的方法

在项目开发中我们经常会用枚举,一般情况下我们为枚举定义了一些类型在使用的时候都要根据枚举的值来判断,我们可以利用  Attribute 来实现。

在定义枚举的时候增加描述属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/// <summary>
/// 定义接口请求状态枚举。
/// </summary>
public enum StatusCode
{
    /// <summary>
    /// 操作成功。
    /// </summary>
    [EnumDescription("操作成功")]
    Success = 1,
  
    /// <summary>
    /// 操作失败。
    /// </summary>
    [EnumDescription("操作失败")]
    Error = 0
}

EnumDescriptionAttribute 定义如下:

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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
/// <summary>
/// 枚举描述属性,使用 EnumDescriptionAttribute 以透明获取的枚举值描述信息。
/// </summary>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class EnumDescriptionAttribute : Attribute
{
    #region Fields...
 
    /// <summary>
    /// 初始化枚举值描述文本缓存。
    /// </summary>
    private static Dictionary<string, string> dic = new Dictionary<string, string>();
 
    #endregion
 
    #region Properties...
 
    /// <summary>
    /// 获取或设置枚举值描述文本。
    /// </summary>
    public string Description{ get; set; }
 
    #endregion
 
    #region Methods...
 
    /// <summary>
    /// 获取指定枚举值的描述文本。
    /// </summary>
    /// <param name="enumValue">指定枚举值。</param>
    /// <returns>指定枚举值的描述文本。</returns>
    public virtual string GetDescription(object enumValue)
    {
        if (enumValue != null)
        {
            return Description ?? enumValue.ToString();
        }
        else
        {
            return String.Empty;
        }
    }
 
    /// <summary>
    /// 获取指定枚举值的描述文本。
    /// </summary>
    /// <param name="enumValue">指定枚举值。</param>
    /// <returns>指定枚举值的描述文本。</returns>
    public static string GetDescription(Enum enumValue)
    {
        //获取指定枚举值的枚举类型。
        Type type = enumValue.GetType();
 
        string key = GetCacheKey(type, enumValue.ToString());
        //如果缓存存在,直接返回缓存的枚举值描述文本。
        if (dic.ContainsKey(key))
        {
            return dic[key];
        }
 
        FieldInfo fieldInfo = type.GetField(enumValue.ToString());
        if (fieldInfo != null)
        {
            //获得枚举中各个字段的定义数组
            var atts = (EnumDescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);
            if (atts.Length > 0)
            {
                dic[key] = atts[0].Description;
                return atts[0].Description;
            }
        }
        return enumValue.ToString();
 
    }
 
    /// <summary>
    /// 以得到指定枚举类型的所有枚举值的由 EnumDescriptionAttribute 或其继承类标注的描述信息
    /// </summary>
    /// <param name="enumType"></param>
    /// <param name="enumIntValue"></param>
    /// <returns></returns>
    public static string GetDescription(Type enumType, int enumIntValue)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        Dictionary<int, string> descs = EnumDescriptionAttribute.GetDescriptions(enumType);
        Dictionary<int, string>.Enumerator en = descs.GetEnumerator();
        while (en.MoveNext())
        {
            if ((enumIntValue & en.Current.Key) == en.Current.Key)
            {
                if (sb.Length == 0)
                {
                    sb.Append(en.Current.Value);
                }
                else
                {
                    sb.Append(',');
                    sb.Append(en.Current.Value);
                }
            }
        }
 
        return sb.ToString();
    }
 
    public static Dictionary<int, string> GetDescriptions(Type enumType)
    {
        Dictionary<int, string> descs = new Dictionary<int, string>();
 
        if (enumType != null && enumType.IsEnum)
        {
            FieldInfo[] fields = enumType.GetFields();
 
            for (int i = 1; i < fields.Length; ++i)
            {
                object fieldValue = Enum.Parse(enumType, fields[i].Name);
                object[] attrs = fields[i].GetCustomAttributes(true);
                bool findAttr = false;
                foreach (object attr in attrs)
                {
                    if (typeof(EnumDescriptionAttribute).IsAssignableFrom(attr.GetType()))
                    {
                        descs.Add((int)fieldValue, ((EnumDescriptionAttribute)attr).GetDescription(fieldValue));
                        findAttr = true;
                        break;
                    }
                }
                if (!findAttr)
                {
                    descs.Add((int)fieldValue, fieldValue.ToString());
                }
            }
        }
 
        return descs;
    }
 
    #region Private Methods...
 
    /// <summary>
    /// 获取指定枚举值描述文本缓存键。
    /// </summary>
    /// <param name="type">指定枚举类型。</param>
    /// <param name="enumStrValue">指定枚举值字符串。</param>
    /// <returns>指定枚举值描述文本缓存键。</returns>
    private static string GetCacheKey(Type type, string enumStrValue)
    {
        return type.ToString() + "_" + enumStrValue;
    }
 
    #endregion
 
    #endregion
}

在使用的时候只需要调用 GetDescription 方法即可。

1
EnumDescriptionAttribute.GetDescription(StatusCode.Success)
posted @   Charles Zhang  阅读(25908)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示