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 ...
随机推荐
- WebApi返回Json格式字符串
WebApi返回json格式字符串, 在网上能找到好几种方法, 其中有三种普遍的方法, 但是感觉都不怎么好. 先贴一下, 网上给的常用方法吧. 方法一:(改配置法) 找到Global.asax文件,在 ...
- python 数据类型 --- 集合
1. 注意列表和集合的区别 set 列表表现形式: list_1 = [1,3,4]; 集合表现形式:set_1= set() list_1 = [1,2,3,4,23,4,2] print(lis ...
- 【夯实PHP基础】PHP常用类和函数总结
本文地址 代码提纲: 1. 字符串处理类及函数 2. 数组处理类及函数 3 .web处理类及函数 将常用的PHP的类和函数总结到这里,主要是 自己用过的,比较有感觉. 1. [字符串处理] 1)[ut ...
- BPM体系文件管理解决方案分享
一.方案概述 企业管理在很大程度上是通过文件化的形式表现出来,体系文件管理是管理体系存在的基础和证据,是规范企业管理活动和全体人员行为,达到管理目标的管理依据.对与公司质量.环境.职业健康安全等体系有 ...
- v14.0\AspNet\Microsoft.Web.AspNet.Props 找不到
错误 E:\Github\AutoMapper\src\AutoMapper\AutoMapper.CoreCLR.kproj : error : 未找到导入的项目"C:\Program ...
- POJ3693 Maximum repetition substring [后缀数组 ST表]
Maximum repetition substring Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 9458 Acc ...
- 最小生成树(Kruskal算法-边集数组)
以此图为例: package com.datastruct; import java.util.Scanner; public class TestKruskal { private static c ...
- Jexus 服务器部署导航
说明:本索引只是方便本人查找,不涉及版权问题,所有博客,还是到元博客地址访问. <script async src="//pagead2.googlesyndication.com/p ...
- App开发的新趋势
移动开发这些年,移动开发者人数越来越多,类似的培训公司发展也很快,不过伴随着的是移动应用的需求这几年发展更为旺盛.要开发好的App,纯原生开发肯定是最佳选择.但是这么多年发展,原生开发的难度并没有降低 ...
- ABP文档 - Web Api 控制器
文档目录 本节内容: 简介 AbpApiController 基类 本地化 其它 过滤 审计日志 授权 防伪造过滤 工作单元 结果包装和异常处理 结果缓存 验证 模块绑定器 简介 通过Abp.Web. ...