c# 枚举类型转换-枚举值、名称、描述转换,转换名称集合和描述集合

文章介绍了如何在C#中进行枚举值与名称、描述之间的转换。包括使用Enum.Parse方法安全转换枚举值,通过反射获取枚举的Description属性,以及将描述转换回枚举值的方法。此外,还提供了获取枚举所有项的名称和描述集合的辅助函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

枚举单个值类型转换

定义一个测试枚举


 enum MyEnum
        {
            [Description("测试1")]
            Test1,
            [Description("测试2")]
            Test2,
            [Description("测试3")]
            Test3,
        }

名称转换成枚举值

名称("Test1")转枚举值(MyEnum.Test1)
最简单的做法:使用(T)Enum.Parse(typeof(T), name)方法, name中传入名称,这种情况如果name不属于当前枚举的值,会发生报错,可以通过反射Type类型中的方法GetFields(BindingFlags.Static | BindingFlags.Public)获取该枚举的所有字段信息FieldInfo,查找是否存在该名称的字段信息,如果不存在返回默认值,存在则返回对象。

		 /// <summary>
        /// 通过名称转换成枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumStr">枚举的名称</param>
        /// <returns></returns>
        public static T ConvertToEnum<T>(string enumStr)
        {
            var fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
            var field = fields.FirstOrDefault(w => w.Name == enumStr);
            if (field == null)
                return default(T);
            return (T)Enum.Parse(typeof(T), field.Name);
        }

枚举值转中文描述(Description)

根据枚举的值获取值上方添加的[Description]标签中的中文描述

方法:通过反射Type类型中的GetField方法获取当前值的字段信息FieldInfo对象,获取当前通过Attribute.GetCustomAttribute方法来获取当前字段的DescriptionAttribute特性,如果存在就返回该特性的Description值。

		/// <summary>
        /// 获取枚举值的描述(需要添加[Description]特性),作为枚举类型的扩展方法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum value)
        {
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name != null)
            {
                FieldInfo field = type.GetField(name);
                if (field != null)
                {
                    DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (attr != null)
                    {
                        return attr.Description;
                    }
                }
            }
            return null;


        }

描述(Description)转换成枚举值

根据描述的字符串([Description("测试1")])来获取对应的枚举值(MyEnum.Test1
方法:通过反射Type类型中的方法GetFields(BindingFlags.Static | BindingFlags.Public)获取所有的字段信息集合,再通过字段信息FieldInfo的GetCustomAttribute``方法遍历查找有DescriptionAttributeDescription 等于传入的中文描述字符串,找到对应的字段信息,就返回该字段实例(T)Enum.Parse(typeof(T), field.Name)

	 	/// <summary>
        /// 将描述转成枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="desc"></param>
        /// <returns></returns>
        public static T EnumConvertByDescription<T>(string desc)
        {
            var fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
            var field = fields.FirstOrDefault(w => (w.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute)?.Description == desc);
            if (field == null)
                return default(T);
            return (T)Enum.Parse(typeof(T), field.Name);
        }

        /// <summary>
        /// 将描述转成枚举
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="desc"></param>
        /// <returns></returns>
        public static object EnumConvertByDescription(Type type,string desc)
        {
            var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
            var field = fields.FirstOrDefault(w => (w.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute)?.Description == desc);
            if (field == null)
                return null;
            return Enum.Parse(type, field.Name);
        }

枚举所有项转换成集合

枚举所有项转换成名称集合

主要使用Enum.GetNames方法

  		/// <summary>
        /// 获取枚举项的字符串集合
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns></returns>
        public static List<string> GetEnumContents<T>() where T : Enum
        {
            return Enum.GetNames(typeof(T)).ToList();
        }

枚举所有项转描述集合

获取枚举值的对象集合,然后调用上面写的GetDescription扩展方法,将对象集合转换成描述集合

        /// <summary>
        /// 获取枚举所有项的描述集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<string> GetEnumDescriptions<T>() where T : Enum
        {

            return Enum.GetValues(typeof(T)).Cast<Enum>().Select(x => x.GetDescription()).ToList();
        }

完整代码-枚举帮助类

 	/// <summary>
    /// 枚举帮助类
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举项的字符串集合
        /// </summary>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns></returns>
        public static List<string> GetEnumContents<T>() where T : Enum
        {
            return Enum.GetNames(typeof(T)).ToList();
        }

        /// <summary>
        /// 获取枚举所有项的描述集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<string> GetEnumDescriptions<T>() where T : Enum
        {

            return Enum.GetValues(typeof(T)).Cast<Enum>().Select(x => x.GetDescription()).ToList();
        }

        /// <summary>
        /// 获取枚举值的描述(需要添加[Description]特性)
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum value)
        {
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name != null)
            {
                FieldInfo field = type.GetField(name);
                if (field != null)
                {
                    DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (attr != null)
                    {
                        return attr.Description;
                    }
                }
            }
            return null;


        }

        /// <summary>
        /// 将描述转成枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="desc"></param>
        /// <returns></returns>
        public static T EnumConvertByDescription<T>(string desc)
        {
            var fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
            var field = fields.FirstOrDefault(w => (w.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute)?.Description == desc);
            if (field == null)
                return default(T);
            return (T)Enum.Parse(typeof(T), field.Name);
        }

        /// <summary>
        /// 通过名称转换成枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="enumStr">枚举的名称</param>
        /// <returns></returns>
        public static T ConvertToEnum<T>(string enumStr)
        {
            var fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);
            var field = fields.FirstOrDefault(w => w.Name == enumStr);
            if (field == null)
                return default(T);
            return (T)Enum.Parse(typeof(T), enumStr);
        }


        /// <summary>
        /// 将描述转成枚举
        /// </summary>
        /// <param name="type">类型</param>
        /// <param name="desc"></param>
        /// <returns></returns>
        public static object EnumConvertByDescription(Type type,string desc)
        {
            var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
            var field = fields.FirstOrDefault(w => (w.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute)?.Description == desc);
            if (field == null)
                return null;
            return Enum.Parse(type, field.Name);
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海盗Sharp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值