c# 枚举返回字符串操作
//内部类
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; } }
// 枚举定义
// 调用方法
String strKufen = EnuHelper.GetDescription(MessageInfo.Send); public enum MessageInfo { [EnumDescription("Send")] Send, [EnumDescription("Received")] Received } [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; } }