zhengyiming
2025-04-10 0846b628ebd2e657a7fb070df41569d38556a476
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
 
namespace LifePayment.Domain.Shared;
 
/// <summary>
/// 枚举拓展
/// </summary>
public static partial class EnumExtension
{
    // 枚举显示字典缓存
    private static readonly ConcurrentDictionary<Type, Dictionary<int, string>> EnumDisplayValueDict = new();
 
    // 枚举值字典缓存
    private static readonly ConcurrentDictionary<Type, Dictionary<int, string>> EnumNameValueDict = new();
 
    // 枚举类型缓存
    private static ConcurrentDictionary<string, Type> _enumTypeDict;
 
    /// <summary>
    /// 获取枚举对象Key与名称的字典(缓存)
    /// </summary>
    /// <param name="enumType"></param>
    /// <returns></returns>
    public static Dictionary<int, string> GetEnumDictionary(this Type enumType)
    {
        if (!enumType.IsEnum)
            throw new ArgumentException("Type '" + enumType.Name + "' is not an enum.");
 
        // 查询缓存
        var enumDic = EnumNameValueDict.ContainsKey(enumType) ? EnumNameValueDict[enumType] : new Dictionary<int, string>();
        if (enumDic.Count != 0)
            return enumDic;
 
        // 取枚举类型的Key/Value字典集合
        enumDic = GetEnumDictionaryItems(enumType);
 
        // 缓存
        EnumNameValueDict[enumType] = enumDic;
 
        return enumDic;
    }
 
    /// <summary>
    /// 获取枚举对象Key与名称的字典
    /// </summary>
    /// <param name="enumType"></param>
    /// <returns></returns>
    private static Dictionary<int, string> GetEnumDictionaryItems(this Type enumType)
    {
        // 获取类型的字段,初始化一个有限长度的字典
        var enumFields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
        Dictionary<int, string> enumDic = new(enumFields.Length);
 
        // 遍历字段数组获取key和name
        foreach (var enumField in enumFields)
        {
            var intValue = (int)enumField.GetValue(enumType);
            enumDic[intValue] = enumField.Name;
        }
 
        return enumDic;
    }
 
    /// <summary>
    /// 获取枚举类型key与描述的字典(缓存)
    /// </summary>
    /// <param name="enumType"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public static Dictionary<int, string> GetEnumDescDictionary(this Type enumType)
    {
        if (!enumType.IsEnum)
            throw new ArgumentException("Type '" + enumType.Name + "' is not an enum.");
 
        // 查询缓存
        var enumDic = EnumDisplayValueDict.ContainsKey(enumType)
                                         ? EnumDisplayValueDict[enumType]
                                         : new Dictionary<int, string>();
 
        if (enumDic.Count != 0)
            return enumDic;
 
        // 取枚举类型的Key/Value字典集合
        enumDic = GetEnumDescDictionaryItems(enumType);
 
        // 缓存
        EnumDisplayValueDict[enumType] = enumDic;
 
        return enumDic;
    }
 
    /// <summary>
    /// 获取枚举类型key与描述的字典(没有描述则获取name)
    /// </summary>
    /// <param name="enumType"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    private static Dictionary<int, string> GetEnumDescDictionaryItems(this Type enumType)
    {
        // 获取类型的字段,初始化一个有限长度的字典
        var enumFields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
        Dictionary<int, string> enumDic = new(enumFields.Length);
 
        // 遍历字段数组获取key和name
        foreach (var enumField in enumFields)
        {
            var intValue = (int)enumField.GetValue(enumType);
            var desc = enumField.GetCustomAttribute<DescriptionAttribute>();
            enumDic[intValue] = desc != null && !string.IsNullOrEmpty(desc.Description) ? desc.Description : enumField.Name;
        }
 
        return enumDic;
    }
 
    /// <summary>
    /// 从程序集中查找指定枚举类型
    /// </summary>
    /// <param name="assembly"></param>
    /// <param name="typeName"></param>
    /// <returns></returns>
    public static Type TryToGetEnumType(Assembly assembly, string typeName)
    {
        // 枚举缓存为空则重新加载枚举类型字典
        _enumTypeDict ??= LoadEnumTypeDict(assembly);
 
        // 按名称查找
        return _enumTypeDict.ContainsKey(typeName) ? _enumTypeDict[typeName] : null;
    }
 
    /// <summary>
    /// 从程序集中加载所有枚举类型
    /// </summary>
    /// <param name="assembly"></param>
    /// <returns></returns>
    private static ConcurrentDictionary<string, Type> LoadEnumTypeDict(Assembly assembly)
    {
        // 取程序集中所有类型
        var typeArray = assembly.GetTypes();
 
        // 过滤非枚举类型,转成字典格式并返回
        var dict = typeArray.Where(o => o.IsEnum).ToDictionary(o => o.Name, o => o);
        ConcurrentDictionary<string, Type> enumTypeDict = new(dict);
        return enumTypeDict;
    }
 
    /// <summary>
    /// 获取枚举的Description
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string GetDescription<T>(this T value) where T : Enum
    {
        return GetEnumDescDictionary(typeof(T))[value.GetHashCode()];
    }
 
    /// <summary>
    /// 获取枚举的Description
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string GetDescription(this object value)
    {
        if (value == null)
        {
            return null;
        }
        return value.GetType().GetMember(value.ToString() ?? string.Empty).FirstOrDefault()
                             ?.GetCustomAttribute<DescriptionAttribute>()?.Description;
    }
 
    /// <summary>
    /// 将枚举转成枚举信息集合
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static List<EnumEntity> EnumToList(this Type type)
    {
        if (!type.IsEnum)
            throw new ArgumentException("Type '" + type.Name + "' is not an enum.");
 
        var arr = System.Enum.GetNames(type);
        return arr.Select(sl =>
        {
            var item = System.Enum.Parse(type, sl);
            return new EnumEntity
            {
                Name = item.ToString(),
                Describe = item.GetDescription() ?? item.ToString(),
                Value = (int)item
            };
        }).ToList();
    }
 
    /// <summary>
    /// 将枚举转成枚举信息集合
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static List<EnumEntity<T>> EnumToList<T>(this Type type)
    {
        if (!type.IsEnum)
            throw new ArgumentException("Type '" + type.Name + "' is not an enum.");
 
        var arr = System.Enum.GetNames(type);
        return arr.Select(sl =>
        {
            var item = System.Enum.Parse(type, sl);
            return new EnumEntity<T>
            {
                Name = item.ToString(),
                Describe = item.GetDescription() ?? item.ToString(),
                Value = (T)item
            };
        }).ToList();
    }
 
    /// <summary>
    /// 枚举ToList
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="type"></param>
    /// <returns></returns>
    public static List<T> EnumToEnumList<T>(this Type type)
    {
        if (!type.IsEnum)
            throw new ArgumentException("Type '" + type.Name + "' is not an enum.");
 
        var arr = System.Enum.GetNames(type);
        return arr.Select(name => (T)System.Enum.Parse(type, name)).ToList();
    }
 
    /// <summary>
    /// 是否是枚举中的值
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool IsEnumValue(this Enum value)
    {
        return Enum.IsDefined(value.GetType(), value);
    }
}
 
/// <summary>
/// 枚举实体
/// </summary>
public class EnumEntity<T>
{
    /// <summary>
    /// 枚举的描述
    /// </summary>
    public string Describe { set; get; }
 
    /// <summary>
    /// 枚举名称
    /// </summary>
    public string Name { set; get; }
 
    /// <summary>
    /// 枚举对象的值
    /// </summary>
    public T Value { set; get; }
}
 
/// <summary>
/// 枚举实体
/// </summary>
public class EnumEntity : EnumEntity<int>
{
 
}
 
/// <summary>
/// 包含枚举类型的枚举信息
/// </summary>
public class EnumEntityAndEnumType<T>
{
    /// <summary>
    /// 枚举类型名称
    /// </summary>
    public string EnumName { get; set; }
 
    /// <summary>
    /// 枚举值明细
    /// </summary>
    public List<EnumEntity<T>> EnumEntitiy { get; set; }
}
 
/// <summary>
/// 包含枚举类型的枚举信息
/// </summary>
public class EnumEntityAndEnumType : EnumEntityAndEnumType<int>
{
 
}