C# Enum.ToString() with complete name

你说的曾经没有我的故事 提交于 2019-11-29 13:45:45
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

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