C#让枚举返回字符串

时间:2022-09-02 20:16:10

下面的手段是使用给枚举项打标签的方式,来返回字符串

下面分别定义一个属性类,和一个枚举帮助类

    [AttributeUsage(AttributeTargets.Field,AllowMultiple = false)]
public sealed class EnumDescriptionAttribute : Attribute
{
private string description;
public string Description { get { return description; } }

public EnumDescriptionAttribute(string description)
: base()
{
this.description = description;
}
}
    public static class EnumHelper    {        public static string GetDescription(Enum value)        {            if (value == null)            {                throw new ArgumentException("value");            }            string description = value.ToString();            var fieldInfo = value.GetType().GetField(description);            var attributes =                (EnumDescriptionAttribute[]) fieldInfo.GetCustomAttributes(typeof (EnumDescriptionAttribute), false);            if (attributes != null && attributes.Length > 0)            {                description = attributes[0].Description;            }            return description;        }    }
使用举例:

enum Week{    [EnumDescription("星期一")]    Monday,    [EnumDescription("星期二")]    Tuesday}//下面打印结果为: 星期一Console.WriteLine(EnuHelper.GetDescription(Week.Monday))