I am searching a solution to get the complete String of an enum.
Example:
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();
So is there a solution?
public static class Extensions
{
public static string GetFullName(this Enum myEnum)
{
return string.Format("{0}.{1}", myEnum.GetType().Name, myEnum.ToString());
}
}
usage:
Color color = Color.Red;
string fullName = color.GetFullName();
Note: I think GetType().Name
is better that GetType().FullName
Try this:
Color color = Color.Red;
string colorString = color.GetType().Name + "." + Enum.GetName(typeof(Color), color);
Fast variant that works for every enum
public static class EnumUtil<TEnum> where TEnum : struct
{
public static readonly Dictionary<TEnum, string> _cache;
static EnumUtil()
{
_cache = Enum
.GetValues(typeof(TEnum))
.Cast<TEnum>()
.ToDictionary(x => x, x => string.Format("{0}.{1}", typeof(TEnum).Name, x));
}
public static string AsString(TEnum value)
{
return _cache[value];
}
}
I have no idea if this is the best way, but it works:
string colorString = string.Format("{0}.{1}", color.GetType().FullName, color.ToString())
colorString = color.GetType().Name + "." + color.ToString();
You can use extension methods.
public static class EnumExtension
{
public static string ToCompleteName(this Color c)
{
return "Color." + c.ToString();
}
}
Now method below will return "Color.Red".
color.ToCompleteName();
http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx
来源:https://stackoverflow.com/questions/18890763/c-sharp-enum-tostring-with-complete-name