天天看点

曲线救国,使枚举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));

不过我没有验证过这样使用的效率问题,以及会不会带来其它的问题,有兴趣的朋友可以研究一下。