Enum Helper
public static class EnumHelper{#region get/// <summary>/// 获得枚举类型所包含的全部项的列表/// </summary>/// <param name="enumType">枚举的类型</param>/// <returns></returns>public static List<EnumItem> GetEnumItems(Type enumType){return GetEnumItems(enumType, false);}/// <summary>/// 获得枚举类型所包含的全部项的列表,包含"All"。/// </summary>/// <param name="enumType">枚举对象类型</param>/// <returns></returns>public static List<EnumItem> GetEnumItemsWithAll(Type enumType){return GetEnumItems(enumType, true);}/// <summary>/// 获得枚举类型所包含的全部项的列表/// </summary>/// <param name="enumType">枚举对象类型</param>/// <param name="withAll">是否需要包含'All'</param>/// <returns></returns>public static List<EnumItem> GetEnumItems(Type enumType, bool withAll){List<EnumItem> list = new List<EnumItem>();if (enumType.IsEnum != true){//whether the type is enum typethrow new InvalidOperationException();}if (withAll == true)list.Add(new EnumItem(-1, "All"));// 获得特性Description的类型信息Type typeDescription = typeof(DescriptionAttribute);// 获得枚举的字段信息(因为枚举的值实际上是一个static的字段的值)System.Reflection.FieldInfo[] fields = enumType.GetFields();// 检索所有字段foreach (FieldInfo field in fields){// 过滤掉一个不是枚举值的,记录的是枚举的源类型if (field.FieldType.IsEnum == false)continue;// 通过字段的名字得到枚举的值int value = (int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null);string text = string.Empty;// 获得这个字段的所有自定义特性,这里只查找Description特性object[] arr = field.GetCustomAttributes(typeDescription, true);if (arr.Length > 0){// 因为Description自定义特性不允许重复,所以只取第一个DescriptionAttribute aa = (DescriptionAttribute)arr[0];// 获得特性的描述值text = aa.Description;}else{// 如果没有特性描述,那么就显示英文的字段名text = field.Name;}list.Add(new EnumItem(value, text));}return list;}/// <summary>/// the the enum value's descrption attribute information/// </summary>/// <param name="enumType">the type of the enum</param>/// <param name="value">the enum value</param>/// <returns></returns>public static string GetDescriptionByEnum<T>(T t){if (t == null){return null;}Type enumType = typeof(T);List<EnumItem> list = GetEnumItems(enumType);foreach (EnumItem item in list){if (Convert.ToInt32(item.Key) == Convert.ToInt32(t))return item.Value.ToString();}return string.Empty;}public static string GetDescriptionByEnum(object t){if (t == null){return string.Empty;}Type enumType = t.GetType();List<EnumItem> list = GetEnumItems(enumType);foreach (EnumItem item in list){if (Convert.ToInt32(item.Key) == Convert.ToInt32(t))return item.Value.ToString();}return string.Empty;}/// <summary>/// get the enum value's int mode value/// </summary>/// <param name="enumType">the type of the enum</param>/// <param name="value">the enum value's descrption</param>/// <returns></returns>public static int GetValueByDescription<T>(string description){Type enumType = typeof(T);List<EnumItem> list = GetEnumItems(enumType);foreach (EnumItem item in list){if (item.Value.ToString().ToLower() == description.Trim().ToLower())return Convert.ToInt32(item.Key);}return -1;}/// <summary>/// get the Enum value according to the its decription/// </summary>/// <param name="enumType">the type of the enum</param>/// <param name="value">the description of the EnumValue</param>/// <returns></returns>public static T GetEnumByDescription<T>(string description){if (description == null){return default(T);}Type enumType = typeof(T);List<EnumItem> list = GetEnumItems(enumType);foreach (EnumItem item in list){if (item.Value.ToString().ToLower() == description.Trim().ToLower())return (T)item.Key;}return default(T);}/// <summary>/// get the description attribute of a Enum value/// </summary>/// <param name="enumType">the type of the enum</param>/// <param name="value">enum value name</param>/// <returns></returns>public static T GetEnumByName<T>(string name){Type enumType = typeof(T);List<EnumItem> list = GetEnumItems(enumType);bool flag = false;foreach (EnumItem item in list){if (item.Value.ToString().ToLower() == name.Trim().ToLower()){flag = true;return (T)item.Key;}}if (!flag){throw new ArgumentException("Can not found specify the name of the enum", "name");}return default(T);}public static T GetEnumByValue<T>(object value){bool flag = false;if (value == null)throw new ArgumentNullException("value");try{Type enumType = typeof(T);List<EnumItem> list = GetEnumItems(enumType);foreach (EnumItem item in list){if (item.Key.ToString().Trim().ToLower() == value.ToString().Trim().ToLower()){flag = true;return (T)item.Key;}}if (!flag){throw new ArgumentException("Can not found specify the value of the enum", "value");} return default(T);}catch{return default(T);}}public static int? GetValueByEnum(object value){if (value == null)return null;try{return (int)value;}catch{return null;}}#endregion #region Parse Enum/// <summary>/// 提供Value的字符,转换为对应的枚举对象/// <remarks>适用于枚举对象值定义为Char类型的</remarks>/// </summary>/// <typeparam name="T"></typeparam>/// <param name="c"></param>/// <returns></returns>public static T Parse<T>(char c) where T : struct{return Parse<T>((ulong)c);}/// <summary>/// 提供Value的字符,转换为对应的枚举对象/// <remarks>适用于枚举对象值定义为Int类型的</remarks>/// </summary>/// <typeparam name="T"></typeparam>/// <param name="l"></param>/// <returns></returns>public static T Parse<T>(ulong l) where T : struct{if (!typeof(T).IsEnum){throw new ArgumentException("Need System.Enum as generic type!");}object o = Enum.Parse(typeof(T), l.ToString());if (Enum.IsDefined(typeof(T), o)){return (T)o;}throw new InvalidCastException();}/// <summary>/// 提供Value的字符,转换为对应的枚举对象/// <remarks>适用于枚举对象值定义为Char类型的</remarks>/// </summary>/// <typeparam name="T"></typeparam>/// <param name="value"></param>/// <returns></returns>public static T Parse<T>(string value) where T : struct{if (value == null || value.Trim().Length != 1){throw new ArgumentException("Invalid cast,value must be one character!");}return Parse<T>(value[0]);}/// <summary>/// /// </summary>/// <typeparam name="T"></typeparam>/// <param name="c"></param>/// <param name="result"></param>/// <returns></returns>public static bool TryParse<T>(char c, out T result) where T : struct{return TryParse<T>((ulong)c, out result);}/// <summary>/// /// </summary>/// <typeparam name="T"></typeparam>/// <param name="value"></param>/// <param name="result"></param>/// <returns></returns>public static bool TryParse<T>(string value, out T result) where T : struct{try{if (value == null || value.Trim().Length != 1){throw new ArgumentException("Invalid cast,value must be one character!");}return TryParse<T>(value[0], out result);}catch{result = default(T);return false;}}/// <summary>/// /// </summary>/// <typeparam name="T"></typeparam>/// <param name="value"></param>/// <param name="result"></param>/// <returns></returns>public static bool TryParse<T>(ulong value, out T result) where T : struct{try{result = Parse<T>(value);return true;}catch{result = default(T);return false;}}#endregion}public class EnumItem{private object m_key;private object m_value;public object Key{get { return m_key; }set { m_key = value; }}public object Value{get { return m_value; }set { m_value = value; }}public EnumItem(object _key, object _value){m_key = _key;m_value = _value;}}
转载于:https://www.cnblogs.com/Wolfmanlq/p/4183428.html
Enum Helper相关推荐
- JAVA线程间通信的几种方式
今天在群里面看到一个很有意思的面试题: "编写两个线程,一个线程打印1~25,另一个线程打印字母A~Z,打印顺序为12A34B56C--5152Z,要求使用线程间的通信." 这是一 ...
- Asp.net Mvc Enum 扩展
消失月余,担心文笔生疏,今作简单一篇小文试手. 一直以来都觉得enum.struct以及class是编程的基础结构. 我们通常意图用枚举来表示一些名称的值属性.有的时候用Enum来填充DropDown ...
- 从零开始开发 VS Code 插件之 Translator Helper
本文目录 Translator Helper 介绍 开发概述 创建第一个VS Code Extension 需求分析 操作文本 调用Google Translation API 实现核心功能 配置命令 ...
- 一起谈.NET技术,一个MVC分页Helper
本人写的一个分页Helper,支持普通分页(也就是,首页.上一页.下一页.末页等),综合分页(普通分页和数字分页的综合).下面是分页效果: 分页代码: PagerHelper.cs 代码 1 us ...
- android studio报错:引入大疆sdk,在真机上允许一闪而过,Logcat报错:Lcom/secneo/sdk/Helper;
引入大疆sdk,编译后在真机上,真机一闪而过.在logcat中可以看到报错如下: 2021-06-28 17:02:57.300 11115-11115/com.bhqd.groundstation ...
- NAT SIP helper
函数nf_nat_sip_init注册SIP协议的NAT helper,用于修改协议报文中的地址和端口信息.如下nf_nat_sip_hooks结构变量sip_hooks,赋值于nf_nat_sip_ ...
- C++ 笔记(07)— 常量(字面常量、const定义常量、constexpr 定义常量、enum 定义常量、define 定义常量)
在 C++ 中,常量类似于变量,只是不能修改.与变量一样,常量也占用内存空间,并使用名称标识为其预留的空间的地址,但不能覆盖该空间的内容. 常量可以是任何的基本数据类型,可分为整型数字.浮点数字.字符 ...
- 《挑战30天C++入门极限》新手入门:C/C++中枚举类型(enum)
新手入门:C/C++中枚举类型(enum) 如果一个变量你需要几种可能存在的值,那么就可以被定义成为枚举类型.之所以叫枚举就是说将变量或者叫对象可能存在的情况也可以说是可能的值一一例举出来. ...
- [C#] enum 枚举
默认情况下,枚举第一个值是0, 可显式为枚举赋值. 可以定义枚举的基础类型,如enum E : short {}, sizeof(E) == 2:默认情况下是int. 枚举的继承链:ValueType ...
- C# Idioms: Enum还是Enum Class(枚举类)
原文排版格式:http://www.marshine.com) reversion:2004/5/28 修改说明:感谢Ninputer提到的CLS兼容问题,同时修改了原来版本没有提及的Equals改写 ...
最新文章
- 优雅地记录http请求和响应的数据
- web release (bat tool)
- 皮一皮:王大爷尽说些大实话...
- sublime text3 最新 license注册码分享 2018
- sql语句添加删除外键
- hibernate jpa_使用Hibernate(JPA)一键式删除
- java拆分单元格_Java 拆分Excel单元格数据为多列
- CardLayout布局练习(小的图片浏览器)
- AIR文件操作(三):使用FileStream对象读写文件
- ASP.NET项目中的驼峰格式JSON响应
- Linux下Birt、JTreeChart中文乱码问题解决办法
- Idea删除未引用包或暴红的包
- 自己不能跑的车凭什么叫自行车?B站硬核up主把自行车做成了自动驾驶
- 数据分析方法,寻找事物之间的因果规律-逻辑关系法(2)
- pyodbc mysql_pyodbc and mySQL
- 【基础知识①】计算机网络知识
- 【华为云计算产品系列】云上迁移工具RainBow实战详解
- 最近喜欢的几款乐器和民谣
- 经典智力题:工人分金条问题
- 显色指数(CRI)计算软件分享(升级版本:增加同步计算R15,CCT,CIE色坐标,三刺激值等)
热门文章
- 自己实践的mac安装python3Linux安装python3
- Redis 最大客户端连接数,你了解吗?
- java -jar命令
- 网页websocket服务器端,node.js中ws模块创建服务端和客户端,网页WebSocket客户端
- server使用abp中调用存储过程 sql_ABP中连接已有数据库执行Sql或存储过程
- python3 numpy二维方法_Python numpy:基于坐标创建二维值数组
- 单片机重要组成部分还有什么,引脚封装分布知识讲解(一)
- 学习单片机入门以后可以做什么?
- java重新打开jframe,Java的; Jframe不重新绘制
- window下git的用户切换_Windows下Git的使用