枚举扩展方法获取枚举Description

枚举扩展方法

复制代码

 1  /// <summary>
 2         /// 扩展方法,获得枚举的Description
 3         /// </summary>
 4         /// <param name="value">枚举值</param>
 5         /// <param name="nameInstend">当枚举没有定义DescriptionAttribute,是否用枚举名代替,默认使用</param>
 6         /// <returns>枚举的Description</returns>
 7         public static string GetDescription(this Enum value, bool nameInstend = true)
 8         {
 9             Type type = value.GetType();
10             string name = Enum.GetName(type, value);
11             if (name==null)
12             {
13                 return null;
14             }
15             FieldInfo field = type.GetField(name);
16             DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
17             if (attribute==null&&nameInstend==true)
18             {
19                 return name;
20             }
21             return attribute==null? null :attribute.Description;
22         }

复制代码

枚举类

复制代码

 1  public enum WeekDay
 2     {
 3         [Description("星期一")]
 4         one=1,
 5         [Description("星期二")]
 6         two =2,
 7         three=3, 
 8    }

复制代码

测试

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

            WeekDay w3 = WeekDay.three;
            string strw2 = w3.GetDescription();// strw3=“three”
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值