C# Enum.ToString() with complete name

后端 未结 6 902
眼角桃花
眼角桃花 2020-12-20 17:26

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;

/         


        
相关标签:
6条回答
  • 2020-12-20 17:36

    Try this:

            Color color = Color.Red;
    
            string colorString = color.GetType().Name + "." + Enum.GetName(typeof(Color), color);
    
    0 讨论(0)
  • 2020-12-20 17:42
     colorString = color.GetType().Name + "." + color.ToString();
    
    0 讨论(0)
  • 2020-12-20 17:46

    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];
        }
    }
    
    0 讨论(0)
  • 2020-12-20 17:46

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

    string colorString = string.Format("{0}.{1}", color.GetType().FullName, color.ToString())
    
    0 讨论(0)
  • 2020-12-20 17:46

    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

    0 讨论(0)
  • 2020-12-20 17:49
    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

    0 讨论(0)
提交回复
热议问题