枚举扩展方法获取枚举Description

时间:2021-07-25 05:02:28
枚举扩展方法
  /// <summary>
/// 扩展方法,获得枚举的Description
/// </summary>
/// <param name="value">枚举值</param>
/// <param name="nameInstend">当枚举没有定义DescriptionAttribute,是否用枚举名代替,默认使用</param>
/// <returns>枚举的Description</returns>
public static string GetDescription(this Enum value, bool nameInstend = true)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name==null)
{
return null;
}
FieldInfo field = type.GetField(name);
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute==null&&nameInstend==true)
{
return name;
}
return attribute==null? null :attribute.Description;
}

枚举类

  public enum WeekDay
{
[Description("星期一")]
one=,
[Description("星期二")]
two =,
three=,
four=,
five=,
six=,
seven= }

测试

           //枚举测试
WeekDay w1 = WeekDay.one;
string strw1 = w1.GetDescription();// strw1= “星期一” WeekDay w3 = WeekDay.three;
string strw2 = w3.GetDescription();// strw3=“three”