You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
3.2 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DS.Module.Core.Extensions
{
public static class EnumExtensions
{
// 枚举显示字典缓存
private static readonly ConcurrentDictionary<Type, Dictionary<string, string>> EnumDisplayValueDict = new();
// 枚举值字典缓存
private static readonly ConcurrentDictionary<Type, Dictionary<string, string>> EnumNameValueDict = new();
// 枚举类型缓存
private static ConcurrentDictionary<string, Type> _enumTypeDict = null;
/// <summary>
/// 获取枚举类型key与描述的字典缓存
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static Dictionary<string, string> GetEnumDescDictionary(Type enumType)
{
if (!enumType.IsEnum)
throw new Exception("该类型不是枚举类型");
// 查询缓存
Dictionary<string, string> enumDic = EnumDisplayValueDict.ContainsKey(enumType) ? EnumDisplayValueDict[enumType] : new Dictionary<string, string>();
if (enumDic.Count == 0)
{
// 取枚举类型的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<string, string> GetEnumDescDictionaryItems(Type enumType)
{
// 获取类型的字段,初始化一个有限长度的字典
FieldInfo[] enumFields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
Dictionary<string, string> enumDic = new(enumFields.Length);
// 遍历字段数组获取key和name
foreach (FieldInfo enumField in enumFields)
{
string fileValue = enumField.Name;
var desc = enumField.GetDescriptionValue<DescriptionAttribute>();
enumDic[fileValue] = desc != null && !string.IsNullOrEmpty(desc.Description) ? desc.Description : enumField.Name;
}
return enumDic;
}
/// <summary>
/// 获取字段特性
/// </summary>
/// <param name="field"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T GetDescriptionValue<T>(this FieldInfo field) where T : Attribute
{
// 获取字段的指定特性,不包含继承中的特性
object[] customAttributes = field.GetCustomAttributes(typeof(T), false);
// 如果没有数据返回null
return customAttributes.Length > 0 ? (T)customAttributes[0] : null;
}
}
}