C#枚举类型的常用操作总结

时间:2021-09-03 00:46:16

标签:   枚举操作   

枚举类型是定义了一组“符号名称/值”配对。枚举类型是强类型的。每个枚举类型都是从system.Enum派生,又从system.ValueType派生,而system.ValueType又从system.Object派生,所以枚举类型是指类型。

编译枚举类型时,C#编译器会把每个符号转换成类型的一个常量字段。C#编译器将枚举类型视为基元类型。

1.获取枚举列表:

        /// <summary>         /// 获取枚举列表         /// </summary>         /// <param name="enumType">枚举的类型</param>         /// <returns>枚举列表</returns>         public static Dictionary<int, string> GetEnumList(Type enumType)         {             var dic = new Dictionary<int, string>();             try             {                 var fd = enumType.GetFields();                 for (var index = 1; index < fd.Length; ++index)                 {                     var info = fd[index];                     var fieldValue = System.Enum.Parse(enumType, fd[index].Name);                     var attrs = info.GetCustomAttributes(typeof(EnumTextAttribute), false);                     foreach (EnumTextAttribute attr in attrs)                     {                         var key = (int)fieldValue;                         if (key == -100) continue;                         var value = attr.Text;                         dic.Add(key, value);                     }                 }                 return dic;             }             catch (Exception ex)             {                 throw new Exception(ex.Message);             }         }

2.获取枚举名称:

        /// <summary>         /// 获取枚举名称         /// </summary>         /// <param name="enumType">枚举的类型</param>         /// <param name="id">枚举值</param>         /// <returns>如果枚举值存在,返回对应的枚举名称,否则,返回空字符</returns>         public static string GetEnumTextById(Type enumType, int id)         {             var ret = string.Empty;             try             {                 var dic = GetEnumList(enumType);                 foreach (var item in dic)                 {                     if (item.Key != id) continue;                     ret = item.Value;                     break;                 }                 return ret;             }             catch (Exception ex)             {                 throw new Exception(ex.Message);             }         }