public static class EnumExtensions
{
public static string GetDescription(this Enum val)
{
var field = val.GetType().GetField(val.ToString());
var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
return customAttribute == null ? val.ToString() : ((DescriptionAttribute)customAttribute).Description;
}
/// <summary>
/// 根据名称获取枚举值
/// </summary>
/// <param name="val">枚举名称</param>
/// <returns></returns>
public static string GetValue(this Enum val)
{
return Convert.ToInt32(Enum.Parse(val.GetType(), val.ToString(), true)).ToString();
}
/// <summary>
/// 根据名称获取枚举名
/// </summary>
/// <param name="val">枚举名称</param>
/// <returns></returns>
public static string GetName(this Enum val)
{
return val.ToString();
}
/// <summary>
/// 检查枚举值是否存在
/// </summary>
/// <param name="val">要检查的枚举值</param>
/// <returns>如果存在则返回 true,否则返回 false</returns>
public static bool IsDefined(this Enum val)
{
var type = val.GetType();
return Enum.IsDefined(type, val);
}
}
使用方法
/// <summary>
/// 会员错误状态信息
/// </summary>
public enum CustomerErrorMsg
{
[Description("注册时,该id已存在")]
UserId已被使用 = 20001,
}
var d2 = CustomerErrorMsg.UserId已被使用.GetName();
var d3 = CustomerErrorMsg.UserId已被使用.GetValue();
var d1 = CustomerErrorMsg.UserId已被使用.GetDescription();