您是第 Web Page Tracking 位访客

水~墨~

昂首阔步,不留一点遗憾!

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

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

即: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();
        }
    }
}

 

 

posted on 2012-08-13 23:15  水墨.MR.H  阅读(1910)  评论(0编辑  收藏  举报
知识共享许可协议
本博客为水墨原创,基于Creative Commons Attribution 2.5 China Mainland License发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的水墨(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言。