using System.Collections.Concurrent;
using System.ComponentModel;
using System.Reflection;
namespace DS.Module.Core;
///
/// 枚举工具类
///
public static class EnumUtil
{
// 枚举显示字典缓存
private static readonly ConcurrentDictionary> EnumShowNameDict = new ConcurrentDictionary>();
///
/// 字符串转Enum
///
/// 枚举
/// 字符串
/// 转换的枚举
public static T ToEnum(this string str)
{
try
{
return (T)Enum.Parse(typeof(T), str);
}
catch
{
return default(T);
}
}
///
/// 获取到对应枚举的描述-没有描述信息,返回枚举值
///
///
///
public static string EnumDescription(this Enum @enum)
{
Type type = @enum.GetType();
string name = Enum.GetName(type, @enum);
if (name == null)
{
return null;
}
FieldInfo field = type.GetField(name);
if (!(Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute))
{
return name;
}
return attribute?.Description;
}
public static int ToEnumInt(this Enum e)
{
try
{
return e.GetHashCode();
}
catch (Exception)
{
return 0;
}
}
///
/// 获取枚举对象Key与名称的字典(缓存)
///
///
///
public static Dictionary GetEnumDictionaryWithKey(this Type enumType)
{
if (!enumType.IsEnum)
throw new ArgumentException("Type '" + enumType.Name + "' is not an enum.");
// 查询缓存
var enumDic = EnumShowNameDict.ContainsKey(enumType) ? EnumShowNameDict[enumType] : new Dictionary();
if (enumDic.Count != 0)
return enumDic;
string[] fieldstrs = Enum.GetNames(enumType);
// 取枚举类型的Key/Value字典集合
enumDic = fieldstrs.Select(item =>
{
object[] arr = enumType.GetField(item).GetCustomAttributes(typeof(DescriptionAttribute), true);
return new
{
Key = item,
Val = ((DescriptionAttribute)arr[0]).Description
};
}).ToDictionary(a => a.Key, b => b.Val);
// 缓存
EnumShowNameDict[enumType] = enumDic;
return enumDic;
}
}