介紹
當將以前的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
