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.

61 lines
1.4 KiB
C#

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