枚举的使用方法
枚举类型在程序开发中是一个非常好用的数据类型,一般用来描述一个审核节点,类型,条件分支是极好的。
我总结枚举类型的使用一般有以下优点:
1. 结构表达清晰
2. 编写条件分支判断不易出错
3. 存储数据空间占用小
1. 定义枚举
byte类型的赋值范围是0~255,对于枚举类型够用了,如果您需要取负值,可以继承int
2. 枚举的使用
3. 获取枚举的Description
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static string GetEnumDescription( this Enum en) { if (en == null ) { return string .Empty; } Type type = en.GetType(); MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object [] attrs = memInfo[0].GetCustomAttributes( typeof (System.ComponentModel.DescriptionAttribute), false ); if (attrs != null && attrs.Length > 0) return ((DescriptionAttribute)attrs[0]).Description; } return en.ToString(); } |
4. 获取枚举类型详细
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /// <summary> /// 获取枚举详细 /// </summary> /// <returns></returns> public static List<EnumDto> GetEnumDescriptions<T>() { List<EnumDto> enumDescriptons = new List<EnumDto>(); if (! typeof (T).IsEnum) throw new Exception( "T不是一个枚举类型" ); foreach ( var value in Enum.GetValues( typeof (T))) { object [] objAttrs = value.GetType().GetField(value.ToString()).GetCustomAttributes( typeof (DescriptionAttribute), true ); string description = "" ; if (objAttrs != null && objAttrs.Length > 0) { DescriptionAttribute descAttr = objAttrs[0] as DescriptionAttribute; description = descAttr.Description; } enumDescriptons.Add( new EnumDto() { Name = value.ToString(), Value = Convert.ToInt32(value), Description = description }); } return enumDescriptons; } |

using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace WoT.Infrastructure.Helper { /// <summary> /// 枚举类型的详细 /// Author:Jacky /// </summary> [DataContract] public class EnumDto { /// <summary> /// 枚举名 /// </summary> [DataMember] public string Name { get; set; } /// <summary> /// 枚举值 /// </summary> [DataMember] public int Value { get; set; } /// <summary> /// 枚举说明 /// </summary> [DataMember] public string Description { get; set; } } }
PS:扫描下方二维码或点击链接,加入QQ群
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步