C#里面经常会用到枚举类型,枚举是值类型对象,如果你想用枚举类型的多属性特性,或者你想在MVC页面上通过简单的值类型转换,将某字段值所代表的含义转换为文字显示,这时候必须要将枚举扩展,是它支持文本描述属性,或者显示名称属性,亦或者多语言支持。例如同一个值类型的字段值,你想让它显示中文描述,英文描述……
 
请看下面的扩展示例:
 
 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#的更多相关文章

  1. 利用DescriptionAttribute定义枚举值的描述信息 z

    System.ComponentModel命名空间下有个名为DescriptionAttribute的类用于指定属性或事件的说明,我所调用的枚举值描述信息就是DescriptionAttribute类 ...

  2. C# 枚举类型的描述信息获取

    新建一个控制台方法,写好自己的枚举类型: 如图: 在里面添加获取描述的方法: 具体源码: 链接:http://pan.baidu.com/s/1nv4rGkp 密码:byz8

  3. .NET获取枚举DescriptionAttribute描述信息性能改进的多种方法

    一. DescriptionAttribute的普通使用方式 1.1 使用示例 DescriptionAttribute特性可以用到很多地方,比较常见的就是枚举,通过获取枚举上定义的描述信息在UI上显 ...

  4. EnumHelper.cs

    网上找的,还比较实用的: using System; using System.Collections.Generic; using System.ComponentModel; using Syst ...

  5. C# 读取枚举描述信息实例

    using System;using System.Collections;using System.Collections.Generic;using System.Linq;using Syste ...

  6. 【点滴积累】通过特性(Attribute)为枚举添加更多的信息

    转:http://www.cnblogs.com/IPrograming/archive/2013/05/26/Enum_DescriptionAttribute.html [点滴积累]通过特性(At ...

  7. c#枚举 获取枚举键值对、描述等

    using System; using System.Collections.Generic; using System.Collections.Specialized; using System.C ...

  8. .net工具类 获取枚举类型的描述

    一般情况我们会用枚举类型来存储一些状态信息,而这些信息有时候需要在前端展示,所以需要展示中文注释描述. 为了方便获取这些信息,就封装了一个枚举扩展类. /// <summary> /// ...

  9. C#枚举扩展方法,获取枚举值的描述值以及获取一个枚举类下面所有的元素

    /// <summary> /// 枚举扩展方法 /// </summary> public static class EnumExtension { private stat ...

随机推荐

  1. java 利用ManagementFactory获取jvm,os的一些信息--转

    原文地址:http://blog.csdn.net/dream_broken/article/details/49759043 想了解下某个Java项目的运行时jvm的情况,可以使用一些监控工具,比如 ...

  2. jQuery2.x源码解析(缓存篇)

    jQuery2.x源码解析(构建篇) jQuery2.x源码解析(设计篇) jQuery2.x源码解析(回调篇) jQuery2.x源码解析(缓存篇) 缓存是jQuery中的又一核心设计,jQuery ...

  3. [原]分享一下我和MongoDB与Redis那些事

    缘起:来自于我在近期一个项目上遇到的问题,在Segmentfault上发表了提问 知识背景: 对不是很熟悉MongoDB和Redis的同学做一下介绍. 1.MongoDB数组查询:MongoDB自带L ...

  4. BPM配置故事之案例9-根据表单数据调整审批线路2

    老李:好久不见啊,小明. 小明:-- 老李:不少部门有物资着急使用,现在的审批流程太慢了,申请时增加一个是否加急的选项吧.如果选加急,金额1000以下的直接到我这里,我审批完就通过,超过1000的直接 ...

  5. PowerShell 数组以及XML操作

    PowerShell基础 PowerShell数组操作 将字符串拆分成数据的操作 cls #原始字符串 $str = "abc,def,ghi,mon" #数据定义 #$StrAr ...

  6. OpenGL ES 3.0: 图元重启(Primitive restart)

    [TOC] 背景概述 在OpenGL绘制图形时,可能需要绘制多个并不相连的图形.这样的情况下这几个图形没法被当做一个图形来处理.也就需要多次调用 DrawArrays 或 DrawElements. ...

  7. 云计算之路-阿里云上:“黑色1秒”最新线索——w3tp与w3dt

    向大家分享一下最近排查“黑色1秒”问题的进展,“黑色1秒”的问题表现详见什么是黑色1秒. 1. 发生在w3wp进程内 判断依据:“黑色1秒”期间,http.sys的HTTP Service Reque ...

  8. CSS currentColor 变量的使用

    CSS中存在一个神秘的变量,少有人知自然也不怎么为人所用.它就是crrentColor变量(或者说是CSS关键字,但我觉得称为变量好理解些). 初识 它是何物?具有怎样的功效?它从哪里来?带着这些疑问 ...

  9. ABP源码分析九:后台工作任务

    文主要说明ABP中后台工作者模块(BackgroundWorker)的实现方式,和后台工作模块(BackgroundJob).ABP通过BackgroundWorkerManager来管理Backgr ...

  10. ABP框架 - 时间

    文档目录 本节内容: 简介 时钟 客户端 时区 客户端 绑定器与转换器 简介 虽然有些应用目标市场只是在一个时区,有些应用目标市场是许多不同时区,为满足这种需求并集中化日期操作,ABP为日期操作提供公 ...