namespace VberZero.Tools.StringModel;
public static class EnumHelper
{
///
/// 根据枚举的名称获取枚举
///
/// 枚举类型
/// 字符串
///
public static TEnum GetEnumByName(this string str) where TEnum : struct
{
if (Enum.TryParse(str, out var result))
{
return result;
}
return default;
}
///
/// 根据枚举获取枚举值
///
/// 枚举类型
/// 枚举
///
public static int ToInt(this TEnum e) where TEnum : struct
{
return Convert.ToInt32(e);
}
///
/// 根据枚举获取枚举值
///
/// 枚举类型
/// 枚举
/// 数字字符串
public static string ToStr(this TEnum e) where TEnum : struct
{
return ToInt(e).ToString();
}
///
/// 根据枚举的值获取枚举名称
///
/// 枚举类型
/// 枚举的值
///
public static string GetEnumName(this int status)
{
return Enum.GetName(typeof(TEnum), status);
}
///
/// 获取枚举名称集合
///
///
///
public static string[] GetNamesArr()
{
return Enum.GetNames(typeof(TEnum));
}
///
/// 将枚举转换成字典集合
///
/// 枚举类型
///
public static Dictionary GetEnumDic()
{
Dictionary resultList = new Dictionary();
Type type = typeof(TEnum);
var strList = GetNamesArr().ToList();
foreach (string key in strList)
{
string val = Enum.Format(type, Enum.Parse(type, key), "d");
resultList.Add(key, int.Parse(val));
}
return resultList;
}
///
/// 将枚举转换成字典
///
///
///
public static Dictionary GetDic()
{
Dictionary dic = new Dictionary();
Type t = typeof(TEnum);
var arr = Enum.GetValues(t);
foreach (var item in arr)
{
dic.Add(item.ToString(), (int)item);
}
return dic;
}
}