using System.ComponentModel;
namespace CommonUtil
{
///
/// 枚举扩展方法
///
public static partial class ExtendUtil
{
///
/// 获取枚举的描述
///
/// 数据
/// string
public static string GetDescription(this System.Enum value)
{
var fi = value.GetType().GetField(value.ToString());
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
return value.ToString();
}
///
/// 获取枚举的value
///
/// 数据
/// int
public static int ToInt(this System.Enum value)
{
return value.GetHashCode();
}
///
/// 获取枚举字符串
///
///
///
public static string GetEnumName(this System.Enum enumName)
{
return enumName.ToString();
}
///
/// 获取枚举字符串
///
///
///
///
public static string GetEnumName(this int enumValue)
{
return System.Enum.GetName(typeof(T), enumValue);
}
///
/// 获取枚举描述
///
/// 枚举类型
///
///
public static string GetDescription(this string enumValue)
{
System.Reflection.FieldInfo field = typeof(T).GetField(enumValue);
//获取描述属性
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
//当描述属性没有时,直接返回名称
if (objs == null || objs.Length == 0)
{
return "";
}
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
return descriptionAttribute.Description;
}
}
}