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 type
throw new InvalidOperationException();
} if (withAll == true)
list.Add(new EnumItem(-, "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 > )
{
// 因为Description自定义特性不允许重复,所以只取第一个
DescriptionAttribute aa = (DescriptionAttribute)arr[]; // 获得特性的描述值
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 -;
} /// <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 != )
{
throw new ArgumentException("Invalid cast,value must be one character!");
} return Parse<T>(value[]);
}
/// <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 != )
{
throw new ArgumentException("Invalid cast,value must be one character!");
} return TryParse<T>(value[], 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;
}
}
Enum Helper的更多相关文章
- C#中Enum的用法
1.定义枚举类型 public enum Test { 男 = 0, 女 = 1 } 2.获取枚举值 public void EnumsAction() { var s = Test.男;//男 va ...
- [ASP.NET MVC 小牛之路]13 - Helper Method
我们平时编程写一些辅助类的时候习惯用“XxxHelper”来命名.同样,在 MVC 中用于生成 Html 元素的辅助类是 System.Web.Mvc 命名空间下的 HtmlHelper,习惯上我们把 ...
- Helper Method
ASP.NET MVC 小牛之路]13 - Helper Method 我们平时编程写一些辅助类的时候习惯用“XxxHelper”来命名.同样,在 MVC 中用于生成 Html 元素的辅助类是 Sys ...
- [2014-09-21]如何在 Asp.net Mvc 开发过程中更好的使用Enum
场景描述 在web开发过程中,有时候需要根据Enum类型生成下拉菜单: 有时候在输出枚举类型的时候,又希望输出对应的更具描述性的字符串. 喜欢直接用中文的请无视本文 不多说,直接看代码. 以下代码借鉴 ...
- C# EnumHelper Enum的值,Description,ToString()的相互转换
首先定义枚举类型,如下: /// <summary> /// 板块 /// </summary> public enum Plate { [Descriptio ...
- Windows解决多版本python执行pip3时出错AttributeError: module 'enum' has no attribute 'IntFlag'?
摘要: 本机装有python2.7和python3.6,执行pip和pip2时没有问题,执行pip3时提示: C:\Users\>pip3 Traceback (most recent call ...
- 微软原版SQL Helper
代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-- ...
- Netfilter 之 连接跟踪的helper
注册helper nf_conntrack_ftp_init是连接跟踪ftp模块的初始化函数,可以看到其调用了nf_conntrack_helpers_register来注册helper: stati ...
- python3 enum模块
枚举是绑定到唯一的常量值的一组符号名称(成员).在枚举中,成员可以通过身份进行比较,枚举本身可以迭代. 1.Enum模块 该模块定义了四个枚举类,可用于定义唯一的名称和值集:Enum,IntEnum, ...
随机推荐
- 解决genemotion模拟器冲突导致的Android Studio无法启动ADB的问题
首先命令行下运行 adb nodaemon server ./adb nodaemon server (Mac OSX) 如果出现错误: error: could not install *smart ...
- 前沿技术解密——VirtualDOM
作为React的核心技术之一Virtual DOM,一直披着神秘的面纱. 实际上,Virtual DOM包含: Javascript DOM模型树(VTree),类似文档节点树(DOM) DOM模型树 ...
- 在GridView中使用radioButoon
在GridView中使用radioButoon 方法一: <input type="radio" id='radioSelectFeed' name="radioD ...
- 使用proxool 连接池:No suitable driver found for proxool
使用proxool连接池时:报错误No suitable driver found for proxool.shide的原因: ①.WEB-INF目录下的lib中没有proxool连接池jar驱动包. ...
- 让Mac也能拥有apt-get类似的功能——Brew
之前一直怀念ubuntu下的apt-get,因为实在是方便,需要安装什么,一个命令搞定,相关的依赖包统统由apt-get维护.下载,编译,安装,那叫一个痛快.什么软件用着不爽,一个命令卸载! 怀念ap ...
- WinStore开发知识导航集锦
1.页面导航与页面传值:http://blog.csdn.net/tcjiaan/article/details/7895487
- ODAC (V9.5.15) 学习笔记(二十一)数据复制
用TVirtualTable在内存中缓存TOraQuery中的数据,主要应用场景是参照其他数据,需要将TOraQuery中的数据复制到TVirtualTable,由于没有类似于TClientDataS ...
- DSP中CMD文件
DSP中CMD文件 (2012-12-26 20:54:17) 转载▼ 标签: 杂谈 分类: DSP FPGA DSP的存储器的地址范围,CMD是主要是根据那个来编的.CMD 它是用来分配rom和ra ...
- oracle rac理解和用途扩展
Oracle RAC的优势在于利用多个节点(数据库实例)组成一个数据库,这样在保证了数据库高可用性的情况下更充分的利用了多个主机的性能,而且可以通过增加节点进行性能的扩展.实现Oracle RAC需要 ...
- Linux查看系统信息命令汇总
# uname -a # 查看内核/操作系统/CPU信息 # /etc/issue # 查看操作系统版本 # cat /proc/cpuinfo # 查看CPU信息 # hostname # 查看计算 ...