EnumHelper.cs枚举助手(枚举描述信息多语言支持)C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Web.Mvc;
using System.Collections.Specialized; namespace ZCPT.CrowdFunding.Web.Extension
{
/// <summary>
/// 枚举助手
/// 熊学浩
/// </summary>
public static class EnumHelper
{
#region Field private static ConcurrentDictionary<Type, Dictionary<int, string>> enumDisplayValueDict = new ConcurrentDictionary<Type, Dictionary<int, string>>();
private static ConcurrentDictionary<Type, Dictionary<string, int>> enumValueDisplayDict = new ConcurrentDictionary<Type, Dictionary<string, int>>();
private static ConcurrentDictionary<Type, Dictionary<int, string>> enumNameValueDict = new ConcurrentDictionary<Type, Dictionary<int, string>>();
private static ConcurrentDictionary<Type, Dictionary<string, int>> enumValueNameDict = new ConcurrentDictionary<Type, Dictionary<string, int>>(); private static ConcurrentDictionary<Type, Dictionary<int, Tuple<string, int>>> enumSeqDisplayValueDict = new ConcurrentDictionary<Type, Dictionary<int, Tuple<string, int>>>();
private static ConcurrentDictionary<string, Type> enumTypeDict = null; #endregion #region Method
/// <summary>
/// 获取枚举对象Key与显示名称的字典
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static Dictionary<int, string> GetEnumDictionary(Type enumType)
{
if (!enumType.IsEnum)
throw new Exception("给定的类型不是枚举类型"); Dictionary<int, string> names = enumNameValueDict.ContainsKey(enumType) ? enumNameValueDict[enumType] : new Dictionary<int, string>(); if (names.Count == )
{
names = GetEnumDictionaryItems(enumType);
enumNameValueDict[enumType] = names;
}
return names;
} private static Dictionary<int, string> GetEnumDictionaryItems(Type enumType)
{
FieldInfo[] enumItems = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
Dictionary<int, string> names = new Dictionary<int, string>(enumItems.Length); foreach (FieldInfo enumItem in enumItems)
{
int intValue = (int)enumItem.GetValue(enumType);
names[intValue] = enumItem.Name;
}
return names;
} /// <summary>
/// 获取枚举对象显示名称与Key的字典
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static Dictionary<string, int> GetEnumValueNameItems(Type enumType)
{
if (!enumType.IsEnum)
throw new Exception("给定的类型不是枚举类型"); Dictionary<string, int> values = enumValueNameDict.ContainsKey(enumType) ? enumValueNameDict[enumType] : new Dictionary<string, int>(); if (values.Count == )
{
values = TryToGetEnumValueNameItems(enumType);
enumValueNameDict[enumType] = values;
}
return values;
} private static Dictionary<string, int> TryToGetEnumValueNameItems(Type enumType)
{
FieldInfo[] enumItems = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
Dictionary<string, int> values = new Dictionary<string, int>(enumItems.Length); foreach (FieldInfo enumItem in enumItems)
{
int intValue = (int)enumItem.GetValue(enumType);
values[enumItem.Name] = intValue;
}
return values;
} /// <summary>
/// 获取枚举对象的值内容
/// </summary>
/// <param name="enumType"></param>
/// <param name="display"></param>
/// <returns></returns>
public static int TryToGetEnumValueByName(this Type enumType, string name)
{
if (!enumType.IsEnum)
throw new Exception("给定的类型不是枚举类型");
Dictionary<string, int> enumDict = GetEnumValueNameItems(enumType);
return enumDict.ContainsKey(name) ? enumDict[name] : enumDict.Select(d => d.Value).FirstOrDefault();
} /// <summary>
/// 获取枚举类型
/// </summary>
/// <param name="assembly"></param>
/// <param name="typeName"></param>
/// <returns></returns>
public static Type TrytoGetEnumType(Assembly assembly, string typeName)
{
enumTypeDict = enumTypeDict ?? LoadEnumTypeDict(assembly);
if (enumTypeDict.ContainsKey(typeName))
{
return enumTypeDict[typeName];
}
return null;
} private static ConcurrentDictionary<string, Type> LoadEnumTypeDict(Assembly assembly)
{
Type[] typeArray = assembly.GetTypes();
Dictionary<string, Type> dict = typeArray.Where(o => o.IsEnum).ToDictionary(o => o.Name, o => o);
ConcurrentDictionary<string, Type> enumTypeDict = new ConcurrentDictionary<string, Type>(dict);
return enumTypeDict;
} #endregion
/// <summary>
/// 枚举显示名(属性扩展)
/// </summary>
public class EnumDisplayNameAttribute : Attribute
{
private string _displayName; public EnumDisplayNameAttribute(string displayName)
{
this._displayName = displayName;
} public string DisplayName
{
get { return _displayName; }
}
} public class EnumExt
{
/// <summary>
/// 根据枚举成员获取自定义属性EnumDisplayNameAttribute的属性DisplayName
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static string GetEnumDisplayName(object o)
{
//获取枚举的Type类型对象
Type t = o.GetType(); //获取枚举的所有字段
FieldInfo[] ms = t.GetFields(); //遍历所有枚举的所有字段
foreach (FieldInfo f in ms)
{
if (f.Name != o.ToString())
{
continue;
} //第二个参数true表示查找EnumDisplayNameAttribute的继承链
if (f.IsDefined(typeof(EnumDisplayNameAttribute), true))
{
return
(f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), true)[] as EnumDisplayNameAttribute)
.DisplayName;
}
} //如果没有找到自定义属性,直接返回属性项的名称
return o.ToString();
} /// <summary>
/// 根据枚举转换成SelectList
/// </summary>
/// <param name="enumType">枚举</param>
/// <returns></returns>
public static List<SelectListItem> GetSelectList(Type enumType)
{
List<SelectListItem> selectList = new List<SelectListItem>();
foreach (object e in Enum.GetValues(enumType))
{
selectList.Add(new SelectListItem() { Text = GetDescription(e), Value = ((int)e).ToString() });
}
return selectList;
}
} /// <summary>
/// 根据枚举转换成SelectList并且设置默认选中项
/// </summary>
/// <param name="enumType"></param>
/// <param name="ObjDefaultValue">默认选中项</param>
/// <returns></returns>
public static List<SelectListItem> GetSelectList(Type enumType, object ObjDefaultValue)
{
int defaultValue = Int32.Parse(ObjDefaultValue.ToString());
List<SelectListItem> selectList = new List<SelectListItem>();
foreach (object e in Enum.GetValues(enumType))
{
try
{
if ((int)e == defaultValue)
{
selectList.Add(new SelectListItem() { Text = GetDescription(e), Value = ((int)e).ToString(), Selected = true });
}
else
{
selectList.Add(new SelectListItem() { Text = GetDescription(e), Value = ((int)e).ToString() });
}
}
catch (Exception ex)
{
string exs = ex.Message;
}
}
return selectList;
} /// <summary>
/// 根据枚举转换成SelectList
/// </summary>
/// <param name="enumType">枚举</param>
/// <returns></returns>
public static List<SelectListItem> GetSelectList(Type enumType)
{
List<SelectListItem> selectList = new List<SelectListItem>();
foreach (object e in Enum.GetValues(enumType))
{
selectList.Add(new SelectListItem() { Text = GetDescription(e), Value = ((int)e).ToString() });
}
return selectList;
}
/// <summary>
/// 根据枚举成员获取自定义属性EnumDisplayNameAttribute的属性DisplayName
/// </summary>
/// <param name="objEnumType"></param>
/// <returns></returns>
public static Dictionary<string, int> GetDescriptionAndValue(Type enumType)
{
Dictionary<string, int> dicResult = new Dictionary<string, int>(); foreach (object e in Enum.GetValues(enumType))
{
dicResult.Add(GetDescription(e), (int)e);
} return dicResult;
} /// <summary>
/// 根据枚举成员获取DescriptionAttribute的属性Description
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static string GetDescription(object o)
{
//获取枚举的Type类型对象
Type t = o.GetType(); //获取枚举的所有字段
FieldInfo[] ms = t.GetFields(); //遍历所有枚举的所有字段
foreach (FieldInfo f in ms)
{
if (f.Name != o.ToString())
{
continue;
}
//// Description
// //第二个参数true表示查找EnumDisplayNameAttribute的继承链
// if (f.IsDefined(typeof(EnumDisplayNameAttribute), true))
// {
// return
// (f.GetCustomAttributes(typeof(EnumDisplayNameAttribute), true)[0] as EnumDisplayNameAttribute)
// .DisplayName;
// }
FieldInfo fi = o.GetType().GetField(o.ToString());
try
{
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes != null && attributes.Length > ) ? attributes[].Description : o.ToString();
}
catch
{
return "(Unknow)";
}
} //如果没有找到自定义属性,直接返回属性项的名称
return o.ToString();
} #region 新增扩展方法 /// <summary>
/// 扩展方法:根据枚举值得到相应的枚举定义字符串
/// </summary>
/// <param name="value"></param>
/// <param name="enumType"></param>
/// <returns></returns>
public static String ToEnumString(this int value, Type enumType)
{
NameValueCollection nvc = GetEnumStringFromEnumValue(enumType);
return nvc[value.ToString()];
} /// <summary>
/// 根据枚举类型得到其所有的 值 与 枚举定义字符串 的集合
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static NameValueCollection GetEnumStringFromEnumValue(Type enumType)
{
NameValueCollection nvc = new NameValueCollection();
Type typeDescription = typeof(DescriptionAttribute);
System.Reflection.FieldInfo[] fields = enumType.GetFields();
string strText = string.Empty;
string strValue = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
nvc.Add(strValue, field.Name);
}
}
return nvc;
} /// <summary>
/// 扩展方法:根据枚举值得到属性Description中的描述, 如果没有定义此属性则返回空串
/// </summary>
/// <param name="value"></param>
/// <param name="enumType"></param>
/// <returns></returns>
public static String ToEnumDescriptionString(this int value, Type enumType)
{
NameValueCollection nvc = GetNVCFromEnumValue(enumType);
return nvc[value.ToString()];
} /// <summary>
/// 根据枚举类型得到其所有的 值 与 枚举定义Description属性 的集合
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static NameValueCollection GetNVCFromEnumValue(Type enumType)
{
NameValueCollection nvc = new NameValueCollection();
Type typeDescription = typeof(DescriptionAttribute);
System.Reflection.FieldInfo[] fields = enumType.GetFields();
string strText = string.Empty;
string strValue = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > )
{
DescriptionAttribute aa = (DescriptionAttribute)arr[];
strText = aa.Description;
}
else
{
strText = "";
}
nvc.Add(strValue, strText);
}
}
return nvc;
} #endregion
}
}
EnumHelper.cs枚举助手(枚举描述信息多语言支持)C#的更多相关文章
- 利用DescriptionAttribute定义枚举值的描述信息 z
System.ComponentModel命名空间下有个名为DescriptionAttribute的类用于指定属性或事件的说明,我所调用的枚举值描述信息就是DescriptionAttribute类 ...
- C# 枚举类型的描述信息获取
新建一个控制台方法,写好自己的枚举类型: 如图: 在里面添加获取描述的方法: 具体源码: 链接:http://pan.baidu.com/s/1nv4rGkp 密码:byz8
- .NET获取枚举DescriptionAttribute描述信息性能改进的多种方法
一. DescriptionAttribute的普通使用方式 1.1 使用示例 DescriptionAttribute特性可以用到很多地方,比较常见的就是枚举,通过获取枚举上定义的描述信息在UI上显 ...
- EnumHelper.cs
网上找的,还比较实用的: using System; using System.Collections.Generic; using System.ComponentModel; using Syst ...
- C# 读取枚举描述信息实例
using System;using System.Collections;using System.Collections.Generic;using System.Linq;using Syste ...
- 【点滴积累】通过特性(Attribute)为枚举添加更多的信息
转:http://www.cnblogs.com/IPrograming/archive/2013/05/26/Enum_DescriptionAttribute.html [点滴积累]通过特性(At ...
- c#枚举 获取枚举键值对、描述等
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.C ...
- .net工具类 获取枚举类型的描述
一般情况我们会用枚举类型来存储一些状态信息,而这些信息有时候需要在前端展示,所以需要展示中文注释描述. 为了方便获取这些信息,就封装了一个枚举扩展类. /// <summary> /// ...
- C#枚举扩展方法,获取枚举值的描述值以及获取一个枚举类下面所有的元素
/// <summary> /// 枚举扩展方法 /// </summary> public static class EnumExtension { private stat ...
随机推荐
- 在知乎上看到 Web Socket这篇文章讲得确实挺好,从头看到尾都非常形象生动,一口气看完,没有半点模糊,非常不错
在知乎上看到这篇文章讲得确实挺好,从头看到尾都非常形象生动,一口气看完,没有半点模糊,非常不错,所以推荐给大家,非常值得一读. 作者:Ovear链接:https://www.zhihu.com/que ...
- 安卓客户端a标签长按弹框提示解决办法
昨天工作时候发现一个bug,是关于a标签的,在安卓客户端中,如果是a标签的话,长按会出现一个弹框,如图所示 是因为安卓客户端的长按触发机制,以后进行wap端开发的时候,如果用到跳转页面尽量不要用a标签 ...
- Oracle补全日志(Supplemental logging)
Oracle补全日志(Supplemental logging)特性因其作用的不同可分为以下几种:最小(Minimal),支持所有字段(all),支持主键(primary key),支持唯一键(uni ...
- ubuntu进行子域名爆破
好记性不如烂笔头,此处记录一下,ubuntu进行子域名的爆破. 先记录一个在线的子域名爆破网址,无意中发现,很不错的网址,界面很干净,作者也很用心,很感谢. https://phpinfo.me/do ...
- osi(open system interconnection)模型的通俗理解
OSI模型的理解: 以你和你女朋友以书信的方式进行通信为例. 1.物理层:运输工具,比如火车.汽车. 2.数据链路层:相当于货物核对单,表明里面有些什么东西,接受的时候确认一下是否正确(CRC检验). ...
- hadoop 笔记(zookeeper)
1.安装 需要提前安装java环境,本文下载zookeeper-3.3.6.tar.gz包. 1.1 tar -zxvf zookeeper-3.3.6.tar.gz 1.2 修改conf中的zoo_ ...
- Linux 中我该如何备份系统
系统备份概述 在前面的一些文章中,我反复提到经常会把系统搞崩溃,所以备份系统就是一件不容忽视的事情.由于 Linux 系统本身的优越性,系统的备份和还原还是比较容易的.主要表现在以下方面: Linux ...
- Unity3D和Egret3D的基情
Unity3D依靠多平台发布这个核心特点,目前如日中天,屌丝引擎之王绝无来者.Egret白鹭引擎,也着实在微信上刷了一屏又一屏.这二者似乎风马牛不相及,但是这个无处不搞基的年代,让一切皆有可能. U3 ...
- c++的性能, c#的产能?!鱼和熊掌可以兼得,.NET NATIVE初窥
对于微软开发者来说,每次BUILD大会都是值得期待的.这次也是惊喜满满,除了大众瞩目的WP8.1的发布还有一项会令开发者兴奋的技术出现:.NET NATIVE.下面就来详细了解一下其为何物. [小九的 ...
- Linux命令:ps,netstat,top
ps ps用于查看当前运行的进程.如果想查看动态的进程信息,可以使用top命令.查看详细命令帮助使用man ps. ps最常用的选项组合就是ps aux: # ps aux USER PID %CPU ...