我们知道定义枚举时是不允许带空格等符号的,这样就不利于进行字符串对比。当然可以通过给枚举添加DescriptionAttribute,然后通过fieldinfo读取DescriptionAttribute来获取字符串。
以下是例子
先定义枚举
/// <summary> /// Campaign Mode /// </summary> public enum CampaignModeEnum { /// <summary> /// Inbound /// </summary> [DescriptionAttribute("Inbound")] Inbound, /// <summary> /// Outbound Preview /// </summary> [DescriptionAttribute("Outbound Preview")] Outbound_Preview, /// <summary> /// Outbound Predictive /// </summary> [DescriptionAttribute("Outbound Predictive")] Outbound_Predictive }
编写获取DescriptionAttribute的类
public static class EnumMethod { public static string StringValue(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length > 0) { return attributes[0].Description; } else { return value.ToString(); } } }
这样调用就可以啦!
EnumMethod.StringValue(CampaignModeEnum.Outbound_Predictive);