using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
namespace Test
{
/// <summary>
/// 枚举类型绑定到字典
/// </summary>
public class EnumUtil
{
//枚举缓存池
private static Dictionary<string, Dictionary<int, string>> _cacheEnumList = new Dictionary<string, Dictionary<int, string>>();
public static Dictionary<int, string> EnumToDictionary(Type enumType)
{
string keyName = enumType.FullName;
if (!_cacheEnumList.ContainsKey(keyName))
{
Dictionary<int, string> dict = new Dictionary<int, string>();
foreach (int i in Enum.GetValues(enumType))
{
string name = Enum.GetName(enumType, i);
string showName = "";
object[] attributes = enumType.GetField(name).GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0) showName = ((System.ComponentModel.DescriptionAttribute)attributes[0]).Description;
dict.Add(i, String.IsNullOrEmpty(showName) ? name : showName);
}
//做缓存
object syncObj = new object();
if (!_cacheEnumList.ContainsKey(keyName))
{
lock (syncObj)
{
if (!_cacheEnumList.ContainsKey(keyName))
{
_cacheEnumList.Add(keyName, dict);
}
}
}
}
return _cacheEnumList[keyName];
}
public static string GetEnumShowName(Type enumType, int intValue)
{
return EnumToDictionary(enumType)[intValue];
}
}
[System.AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = false)]
public sealed class EnumShowNameAttribute : Attribute
{
private string showName;
/// <summary>
/// 显示名称
/// </summary>
public string ShowName
{
get { return this.showName; }
}
/// <summary>
/// 构造枚举的显示名称
/// </summary>
/// <param name="showname">显示名称 </param>
public EnumShowNameAttribute(string showname)
{
this.showName = showname;
}
}
}
using System;
using System.ComponentModel;
namespace Test
{
public enum OnlineAuditStatus
{
[Description("未处理 ")]
NotHandle = 0,
[Description("同意 ")]
Agree = 1,
[Description("取消 ")]
Cancel = 2,
[Description("撤销 ")]
Revoke = 3
}
public enum RechargeAudit : long
{
[EnumShowName("未处理 ")]
NotHandle = 0,
[EnumShowName("同意 ")]
Agree = 1,
[EnumShowName("取消 ")]
Cancel = 2,
[EnumShowName("拒绝 ")]
Revoke = 3
}
class Program
{
static void Main()
{
var dict = EnumUtil.EnumToDictionary(typeof(OnlineAuditStatus));
foreach (var item in dict)
{
Console.WriteLine("{0}-{1}", item.Key, item.Value);
}
var dict2 = EnumUtil.GetEnumShowName(typeof(OnlineAuditStatus), 2);
Console.WriteLine(dict2);
Console.ReadLine();
}
}
}