Text description for enum values
来源:互联网 发布:类似汤不热的软件 编辑:程序博客网 时间:2024/05/16 19:38
I wanted to add text descriptions to my enum values; similar to overriding ToString on a class. This is what I came up with, using the beauty of generics: A sample enum implementing my custom description attribute: public enum MyEnum { [EnumDescription("Funky chicken walks again!")] FunkyChicken = 0, [EnumDescription("Doctor?")] Doctor = 1 } This next code block defines the custom attribute: [AttributeUsage(AttributeTargets.Field)] public class EnumDescriptionAttribute : Attribute { private string _text = ""; /// <summary> /// Text describing the enum value /// </summary> public string Text { get { return this._text; } } /// <summary> /// Instantiates the EnumDescriptionAttribute object /// </summary> /// <param name="text">Description of the enum value</param> public EnumDescriptionAttribute(string text) { _text = text; } } Finally, a static method that prints the attribute from any enum, using generics: static StringDictionary _enumDescriptions = new StringDictionary(); public static string GetEnumDescription<EnumType>(EnumType @enum) { Type enumType = @enum.GetType(); string key = enumType.ToString() + "___" + @enum.ToString(); if (_enumDescriptions[key] == null) { FieldInfo info = enumType.GetField(@enum.ToString()); if (info != null) { EnumDescriptionAttribute[] attributes = (EnumDescriptionAttribute[])info.GetCustomAttributes(typeof(EnumDescriptionAttribute), false); if (attributes != null && attributes.Length > 0) { _enumDescriptions[key] = attributes[0].Text; return _enumDescriptions[key]; } } _enumDescriptions[key] = @enum.ToString(); } return _enumDescriptions[key]; } For performance reasons, the StringDictionary is used to cache the values. Reflection tends to be expensive, so why not cache things? :)Text description for enum values
- Text description for enum values
- Enum的得到Description
- java enum values()方法
- 21.4 Enum values and operations
- c# ENUM 通过Description得到Value
- 枚举(Enum)中的values()方法揭秘
- Map enum in JPA with fixed values?
- Enum中values()方法取值顺序
- ENUM values missing in SRSANALYSISENUMS Table
- java枚举enum类中的values()
- 枚举类enum的values()方法
- Supported Values for @SuppressWarnings
- Supported Values for @SuppressWarnings
- Supported Values for @SuppressWarnings
- Job Description For OES Testing
- Simple Description for C Language
- Eclipse loading description for 解决
- Gridview cell text values all Empty Strings
- how to disable alignment trap from user space in linux
- 制作可执行的JAR文件包及jar命令详解zt
- MPLS
- SourceForge
- ASP.NET 2.0客户端回调的实现分析
- Text description for enum values
- DiscuzNT 实体项目(Entity) 简析
- 运营商重组后的号段
- 简单触发器的例子
- PE文件格式分析
- odac组件(437使用)
- 创建主健、外键
- 第14章 Linux终端设备驱动
- linux目录介绍