C# Enum.ToString() with complete name

馋奶兔 提交于 2019-11-28 07:34:09

问题


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?


回答1:


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




回答2:


Try this:

        Color color = Color.Red;

        string colorString = color.GetType().Name + "." + Enum.GetName(typeof(Color), color);



回答3:


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];
    }
}



回答4:


I have no idea if this is the best way, but it works:

string colorString = string.Format("{0}.{1}", color.GetType().FullName, color.ToString())



回答5:


 colorString = color.GetType().Name + "." + color.ToString();



回答6:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!