C#枚举类型,设置对应的中文描述,并且获取其值对应的描述,更新Extension扩展方法

6 篇文章 0 订阅

C#的枚举类型,提供了Description,让你更好的直接这个枚举所代表的意义。

需要引用,using System.ComponentModel;

    public enum EnumStock
    {
        [Description("正常入库")]
        ZCRK = 101,
        [Description("销售退货")]
        XSTH = 102
    }

有的时候,会遇到,给你101,你需要将101转换成 正常入库,这个时候,就需要自己扩展枚举类型。

首先插入如下代码:

    public class EnumHelper
    {
        public static string GetDescription(Enum obj)
        {
            string objName = obj.ToString();
            Type t = obj.GetType();
            System.Reflection.FieldInfo fi = t.GetField(objName);
            System.ComponentModel.DescriptionAttribute[] arrDesc = (System.ComponentModel.DescriptionAttribute[])fi.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);

            return arrDesc[0].Description;
        }
        public static void GetEnum<T>(string a, ref T t)
        {
            foreach (T b in Enum.GetValues(typeof(T)))
            {
                if (GetDescription(b as Enum) == a)
                    t = b;
            }
        }
    }

调用转换,这样就能做转换,将101转换成对应的正常入库

EnumStock type = (EnumStock)Enum.Parse(typeof(EnumStock), “101”);
string typeName = EnumHelper.GetDescription(type);

这样调用较为复杂,可以用Extension扩展方法来进行拓展。

对类进行如下修改,静态类

 public static class EnumHelper
    {
        public static string GetDescription(this Enum obj)
        {
            string objName = obj.ToString();
            Type t = obj.GetType();
            System.Reflection.FieldInfo fi = t.GetField(objName);
            System.ComponentModel.DescriptionAttribute[] arrDesc = (System.ComponentModel.DescriptionAttribute[])fi.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
            return arrDesc[0].Description;
        }
        public static void GetEnum<T>(string a, ref T t)
        {
            foreach (T b in Enum.GetValues(typeof(T)))
            {
                if (GetDescription(b as Enum) == a)
                    t = b;
            }
        }
    }

修改后直接.就会有代码提示,非常的方便

     EnumSumBurnType type = (EnumSumBurnType)Enum.Parse(typeof(EnumSumBurnType), dr["type"].TryParseToString());
     type.GetDescription();

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值