Created
November 27, 2012 14:51
-
-
Save yicone/4154619 to your computer and use it in GitHub Desktop.
enum value map to string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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