using System;
using System.ComponentModel;
using System.Reflection;
namespace DS.Module.Core;
///
/// 枚举工具类
///
public static class EnumUtil
{
///
/// 字符串转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;
}
}
}