天天看點

曲線救國,使枚舉enum支援字元串string

枚舉是不支援string的,有的時候我們需要為枚舉成員指定相應的說明性文字,如我引用SimpleEnum.Today的時候,需要在我的主界面上列印“今天”,而不是“Today”。這樣就使我們在編碼的時候要不停的編寫switch來表示枚舉變量的注釋。那麼,有沒有更好的辦法來維護我們的枚舉成員呢。本文将提供一種解決方法。

例如,有如下枚舉變量:

public enum SimpleEnum

{

Today, //表示今天

Tomorrow, //表示明天

}

我們可以通過為枚舉成員指定屬性,達到一勞永逸。

首先我們需要建立一個EnumDescriptionAttribute類,表示對屬性成員可以指定描述。

/// <summary>

/// Provides a description for an enumerated type.

/// </summary>

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]

public sealed class EnumDescriptionAttribute : Attribute

{

private string description;

public string Description

{

get { return this.description; }

}

/// <summary>

/// Initializes a new instance of the class.

/// </summary>

/// <param name="description"></param>

public EnumDescriptionAttribute(string description)

: base()

{

this.description = description;

}

}

其次,我們需要建立一個EnumHelper類,用于獲得屬性的值。

public static class EnumHelper

{

/// <summary>

/// Gets the <see cref="DescriptionAttribute" /> of an <see cref="Enum" />

/// type value.

/// </summary>

/// <param name="value">The <see cref="Enum" /> type value.</param>

/// <returns>A string containing the text of the

/// <see cref="DescriptionAttribute"/>.</returns>

public static string GetDescription(Enum value)

{

if (value == null)

{

throw new ArgumentNullException("value");

}

string description = value.ToString();

FieldInfo fieldInfo = value.GetType().GetField(description);

EnumDescriptionAttribute[] attributes =

(EnumDescriptionAttribute[])

fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);

if (attributes != null && attributes.Length > 0)

{

description = attributes[0].Description;

}

return description;

}

}

最後,我們将上文介紹的枚舉添加屬性,如下:

public enum SimpleEnum

{

[EnumDescription("表示今天")]

Today, //

[EnumDescription("表示明天")]

Tomorrow, //

}

這個時候,你就可以在任何想要得到這個屬性描述的地方,使用如下語句:

Debug.Print("{0}", EnumHelper.GetDescription(SimpleEnum.Today));

不過我沒有驗證過這樣使用的效率問題,以及會不會帶來其它的問題,有興趣的朋友可以研究一下。