C#Enum.ToString(),名称完整
我正在寻找一个解决方案来获取枚举的完整字符串。
例:
Public Enum Color { Red = 1, Blue = 2 } Color color = Color.Red; // This will always get "Red" but I need "Color.Red" string colorString = color.ToString(); // I know that this is what I need: colorString = Color.Red.ToString();
那么有解决方案吗?
public static class Extensions { public static string GetFullName(this Enum myEnum) { return string.Format("{0}.{1}", myEnum.GetType().Name, myEnum.ToString()); } }
用法:
Color color = Color.Red; string fullName = color.GetFullName();
注意:我认为GetType().Name
比GetType().FullName
更好
适用于每个枚举的快速变体
public static class EnumUtil where TEnum : struct { public static readonly Dictionary _cache; static EnumUtil() { _cache = Enum .GetValues(typeof(TEnum)) .Cast () .ToDictionary(x => x, x => string.Format("{0}.{1}", typeof(TEnum).Name, x)); } public static string AsString(TEnum value) { return _cache[value]; } }
我不知道这是不是最好的方法,但它有效:
string colorString = string.Format("{0}.{1}", color.GetType().FullName, color.ToString())
试试这个:
Color color = Color.Red; string colorString = color.GetType().Name + "." + Enum.GetName(typeof(Color), color);
colorString = color.GetType().Name + "." + color.ToString();
您可以使用扩展方法。
public static class EnumExtension { public static string ToCompleteName(this Color c) { return "Color." + c.ToString(); } }
现在下面的方法将返回“Color.Red”。
color.ToCompleteName();
http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx