using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; namespace OS.Common.Extention { /// /// 枚举扩展方法类 /// public static class EnumExtention { /// /// 获取描述 /// /// 枚举对象 /// 是否二进制取和 /// 多个描述分隔符 /// public static string GetDesp(this Enum en, bool isFlag = false, string operate = ",") { var values = en.GetType().ToEnumDirs(); int current = (int) Enum.Parse(en.GetType(), en.ToString()); if (isFlag) { StringBuilder strResult = new StringBuilder(); foreach (var value in values) { int tempKey = value.Key.ToInt32(); if ((tempKey & current) == tempKey) { if (strResult.Length != 0) { strResult.Append(operate); } strResult.Append(value.Value); } } return strResult.ToString(); } KeyValuePair keypair = values.FirstOrDefault(e => e.Key == current.ToString()); return keypair.Key == null ? "不存在的枚举值" : keypair.Value; } private static ConcurrentDictionary> enumDirs =new ConcurrentDictionary>(); /// /// 获取枚举字典列表 /// /// 枚举类型 /// 返回枚举值是否是int类型 /// public static Dictionary ToEnumDirs(this Type enType, bool isIntValue=true) { if (!enType.IsEnum) { throw new ArgumentException("获取枚举字典,参数必须是枚举类型!"); } string key = string.Concat(enType.FullName, isIntValue); Dictionary dirs; enumDirs.TryGetValue(key, out dirs); if (dirs != null) return dirs.Copy(); dirs=new Dictionary(); var values = Enum.GetValues(enType); foreach (var value in values) { var name = Enum.GetName(enType, value); string resultValue = isIntValue ? ((int)value).ToString() : value.ToString(); var attrList = enType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[]; if (attrList != null && attrList.Length > 0) { dirs.Add(resultValue, attrList[0].Description); continue; } dirs.Add(resultValue, name); } enumDirs.TryAdd(key, dirs); return dirs.Copy(); } /// /// 拷贝字典 /// /// /// private static Dictionary Copy(this Dictionary source) { Dictionary results=new Dictionary(); foreach (var sou in source) { results.Add(sou.Key, sou.Value); } return results; } } }