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.

100 lines
2.7 KiB
C#

using System.Collections.Concurrent;
using System.ComponentModel;
12 months ago
using System.Reflection;
namespace DS.Module.Core;
/// <summary>
/// 枚举工具类
/// </summary>
public static class EnumUtil
{
// 枚举显示字典缓存
private static readonly ConcurrentDictionary<Type, Dictionary<string, string>> EnumShowNameDict = new ConcurrentDictionary<Type, Dictionary<string, string>>();
12 months ago
/// <summary>
/// 字符串转Enum
/// </summary>
/// <typeparam name="T">枚举</typeparam>
/// <param name="str">字符串</param>
/// <returns>转换的枚举</returns>
public static T ToEnum<T>(this string str)
{
try
{
return (T)Enum.Parse(typeof(T), str);
}
catch
{
return default(T);
}
}
/// <summary>
/// 获取到对应枚举的描述-没有描述信息,返回枚举值
/// </summary>
/// <param name="enum"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 获取枚举对象Key与名称的字典缓存
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static Dictionary<string, string> 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<string, string>();
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;
}
12 months ago
}