枚举使用特殊字符

枚举中有些特殊字符不能使用,可以用下面的方法实现。

即:Attribute属性  [Description("application/x-www-form-urlencoded")]

       然后获取属性的 ToString() 获取

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;
namespace common
{
    public class EnumModel
    {
        public enum  enumWebrequestContextType
        {
            [Description("application/x-www-form-urlencoded")]
            form,
            [Description("application/json")]
            json,
            [Description("application/xml")]
            xml
        }
        /// <summary>
        /// 让枚举中使用特殊字符。
        /// 原理:让枚举中的值都拥有Attribute属性,然后通过在属性里设置特殊字符。从而返回属性的ToString()
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static string GetEnumName(Enum en)
        {
            Type temType = en.GetType();
            MemberInfo[] memberInfos = temType.GetMember(en.ToString());
            if (memberInfos != null && memberInfos.Length > 0)
            {
                object[] objs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (objs != null && objs.Length > 0)
                {
                    return ((DescriptionAttribute)objs[0]).Description;
                }
            }
            return en.ToString();
        }
    }
}
原文地址:https://www.cnblogs.com/StudyLife/p/shujuyu.html