C#将Enum枚举映射到文本字符串

介绍

当将以前的C代码移植到C#中时,我快发疯了,因为有很多的数组需要将常量映射到字符串。当我在寻找一个C#的方法来完成的时候,我发现了一个自定义属性和映射的方法。

如何使用代码?

对每一个enum枚举都添加一个Description属性:

private enum MyColors
{
   [Description("yuk!")]       LightGreen    = 0x012020,
   [Description("nice :-)")]   VeryDeepPink  = 0x123456,
   [Description("so what")]    InvisibleGray = 0x456730,
   [Description("no comment")] DeepestRed    = 0xfafafa,
   [Description("I give up")]  PitchBlack    = 0xffffff,
}

为了在代码中读取描述字符串,你可以如下这么做:

public static string GetDescription(Enum value)
{
   FieldInfo fi= value.GetType().GetField(value.ToString()); 
   DescriptionAttribute[] attributes = 
         (DescriptionAttribute[])fi.GetCustomAttributes(
         typeof(DescriptionAttribute), false);
   return (attributes.Length>0)?attributes[0].Description:value.ToString();
}

如果没有下面的using语句,你的代码是不能通过编译的。

using System.ComponentModel;        
using System.Reflection;

好处

代替代码中大量的常量和数组,上面的解决方法保持了预定义和描述在一起,并阅读性也很强。

历史

我仅仅是一个偶然的机会才发现原来FrameWork框架还提供一个DescriptionAttribute类的。当我第一次用我自己定义的属性时,发生了一些冲突,因为我引入了ComponentModel命名空间。

原文地址:http://blog.csdn.net/pengqianhe/article/details/8031679

原文地址:https://www.cnblogs.com/albert1017/p/4239015.html