获取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
}

上一篇:COLUMN_FORMAT 的值:FIXED、DYNAMIC、DEFAULT 的区别(待补充)


下一篇:Elasticsearch【mappings】类型配置操作