C# enum 添加字符串(中文)标记

来源:互联网 发布:mac电脑剪切快捷键 编辑:程序博客网 时间:2024/06/05 14:45

来源:《编写高质量代码改善C#程序的157个建议》-建议110:用类来代替enum

废话不多说,代码来得更亲切。

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace enumDemo{    class Program    {        static void Main(string[] args)        {            Console.WriteLine(((int)week.monday).ToString());            Console.WriteLine(week.monday.ToString());            Console.WriteLine(EnumHelper.GetDescription(week.monday));            Console.WriteLine(((int)week.tuesday).ToString());            Console.WriteLine(week.tuesday.ToString());            Console.WriteLine(EnumHelper.GetDescription(week.tuesday));            if (week.优惠券.ToString().Equals("优惠券"))            {                Console.WriteLine("bingo");            }            Console.ReadLine();        }        enum week        {            [EnumDescription("星期一")]            monday,            [EnumDescription("星期二")]            tuesday,            优惠券        }        #region  添加标记方法        [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]        public sealed class EnumDescriptionAttribute : Attribute        {            private string description;            public string Description            {                get { return this.description; }            }            public EnumDescriptionAttribute(string description)                : base()            {                this.description = description;            }        }        public static class EnumHelper        {            public static string GetDescription(Enum value)            {                if (value == null)                {                    throw new ArgumentNullException("value");                }                string description = value.ToString();                System.Reflection.FieldInfo fieldinfo = value.GetType().GetField(description);                EnumDescriptionAttribute[] attributes = (EnumDescriptionAttribute[])fieldinfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);                if (attributes != null && attributes.Length > 0)                {                    description = attributes[0].Description;                }                return description;            }        }        #endregion        class weekend        {            public static readonly weekend monday = new weekend(0);            public static readonly weekend tuesday = new weekend(1);            private int _infoType;            private weekend(int infoType)            {                _infoType = infoType;            }            public override string ToString()            {                switch (_infoType)                {                    case 0:                        return "星期一";                    case 1:                        return "星期二";                    default:                        throw new Exception("不正确的输入");                }                //return base.ToString();            }        } }}


1 0
原创粉丝点击