C# Enum.ToString() with complete name

后端 未结 6 945
眼角桃花
眼角桃花 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:46

    Fast variant that works for every enum

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

提交回复
热议问题