获取Enum的扩张方法。

public static class EnumExtention
{
/// <summary>
/// 获取枚举的描述信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Dictionary<int, string> GetDescription<T>()
where T : struct, IComparable, IFormattable, IConvertible
{
var t = typeof(T);
if (t.IsEnum)
{

Dictionary<int, string> list = new Dictionary<int, string>();
Array a = Enum.GetValues(t);
for (int i = 0; i < a.Length; i++)
{
string enumName = a.GetValue(i).ToString();
int enumKey = (int)System.Enum.Parse(t, enumName);
string enumDescription = GetDescription(t, enumKey);
list.Add(enumKey, enumDescription);
}
return list;
}
return null;
}

#region 工具函数

private static string GetName(System.Type t, object v)
{
try
{
return Enum.GetName(t, v);
}
catch
{
return "UNKNOWN";
}
}

/// <summary>
/// 返回指定枚举类型的指定值的描述
/// </summary>
/// <param name="t">枚举类型</param>
/// <param name="v">枚举值</param>
/// <returns></returns>
private static string GetDescription(System.Type t, object v)
{
try
{
FieldInfo fi = t.GetField(GetName(t, v));
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : GetName(t, v);
}
catch
{
return "UNKNOWN";
}
}
#endregion
}

转载于:https://www.cnblogs.com/robbert/p/4428965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值