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 ...
 
随机推荐
- 一个技术汪的开源梦 —— 公共组件缓存之分布式缓存 Redis 实现篇
			
Redis 安装 & 配置 本测试环境将在 CentOS 7 x64 上安装最新版本的 Redis. 1. 运行以下命令安装 Redis $ wget http://download.redi ...
 - dagger2系列之Scope
			
Dagger的Scope注解代表的是作用域,通过实现自定义@Scope注解,标记当前生成对象的使用范围,标识一个类型的注射器只实例化一次,在同一个作用域内,只会生成一个实例, 然后在此作用域内共用一个 ...
 - 玩转ajax
			
1.什么是ajax? Ajax 是 Asynchronous JavaScript and XML(以及 DHTML 等)的缩写. 2.ajax需要什么基础? HTML 用于建立 Web 表单并确定应 ...
 - BPM与 SAP & Oracle EBS集成解决方案分享
			
一.需求分析 SAP和Oracle EBS都是作为全球顶级的的ERP产 品,得到了众多客户的青睐.然而由于系统庞大.价格昂贵以及定位不同,客户在实施过程中经常会面临以下困惑: 1.SAP如何实现&qu ...
 - Linux 入门之网络配置
			
查看网络状态 ifconfig 修改网络参数 实验环境centos6.5,其他系统自行百度 ls /etc/sysconfig/network-scripts 显示所有文件, vi /etc/sysc ...
 - SpringMVC初步
			
SpringMVC框架介绍 1) Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面. Spring 框架提供了构建 Web 应用程序的全功 ...
 - Jenkins配置MSBuild实现自动部署(MSBuild+SVN/Subversion+FTP+BAT)
			
所要用到的主要插件: [MSBuild Plugin] 具体操作: 1.配置MSBuild的版本 [系统管理]->[Global Tool Configuration]->[MSBuild ...
 - 用Taurus.MVC 做个企业站(下)
			
前言: 上一篇完成了首页,这一篇就把剩下的几个功能给作了吧. 包括文章列表.文章详情和产品展示. 1:文章列表: 原来的ArticleList.aspx 1:现在的articlelist.html 除 ...
 - 【腾讯优测干货分享】如何降低App的待机内存(二)——规范测试流程及常见问题
			
本文来自于腾讯优测公众号(wxutest),未经作者同意,请勿转载,原文地址:https://mp.weixin.qq.com/s/806TiugiSJvFI7fH6eVA5w 作者:腾讯TMQ专项测 ...
 - Kafka1  利用虚拟机搭建自己的Kafka集群
			
前言: 上周末自己学习了一下Kafka,参考网上的文章,学习过程中还是比较顺利的,遇到的一些问题最终也都解决了,现在将学习的过程记录与此,供以后自己查阅,如果能帮助到其他人,自然是更好的. ...