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