Skip to content

Instantly share code, notes, and snippets.

@yicone
Created November 27, 2012 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yicone/4154619 to your computer and use it in GitHub Desktop.
Save yicone/4154619 to your computer and use it in GitHub Desktop.
enum value map to string
/// <summary>
/// http://stackoverflow.com/questions/2787506/cast-string-to-enum-with-enum-attribute
/// todo: http://www.cnblogs.com/smalldust/archive/2006/04/25/384657.html 利用缓存优化
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetDescription(this Enum value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
string description = value.ToString();
FieldInfo fieldInfo = value.GetType().GetField(description);
DescriptionAttribute[] attributes =
(DescriptionAttribute[])
fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
description = attributes[0].Description;
}
return description;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment