String representation of an Enum

后端 未结 30 1926
不思量自难忘°
不思量自难忘° 2020-11-22 02:44

I have the following enumeration:

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}

T

30条回答
  •  北海茫月
    2020-11-22 03:31

    My variant

    public struct Colors
    {
        private String current;
    
        private static string red = "#ff0000";
        private static string green = "#00ff00";
        private static string blue = "#0000ff";
    
        private static IList possibleColors; 
    
        public static Colors Red { get { return (Colors) red; } }
        public static Colors Green { get { return (Colors) green; } }
        public static Colors Blue { get { return (Colors) blue; } }
    
        static Colors()
        {
            possibleColors = new List() {red, green, blue};
        }
    
        public static explicit operator String(Colors value)
        {
            return value.current;
        }
    
        public static explicit operator Colors(String value)
        {
            if (!possibleColors.Contains(value))
            {
                throw new InvalidCastException();
            }
    
            Colors color = new Colors();
            color.current = value;
            return color;
        }
    
        public static bool operator ==(Colors left, Colors right)
        {
            return left.current == right.current;
        }
    
        public static bool operator !=(Colors left, Colors right)
        {
            return left.current != right.current;
        }
    
        public bool Equals(Colors other)
        {
            return Equals(other.current, current);
        }
    
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (obj.GetType() != typeof(Colors)) return false;
            return Equals((Colors)obj);
        }
    
        public override int GetHashCode()
        {
            return (current != null ? current.GetHashCode() : 0);
        }
    
        public override string ToString()
        {
            return current;
        }
    }
    

    Code looks a bit ugly, but usages of this struct are pretty presentative.

    Colors color1 = Colors.Red;
    Console.WriteLine(color1); // #ff0000
    
    Colors color2 = (Colors) "#00ff00";
    Console.WriteLine(color2); // #00ff00
    
    // Colors color3 = "#0000ff"; // Compilation error
    // String color4 = Colors.Red; // Compilation error
    
    Colors color5 = (Colors)"#ff0000";
    Console.WriteLine(color1 == color5); // True
    
    Colors color6 = (Colors)"#00ff00";
    Console.WriteLine(color1 == color6); // False
    

    Also, I think, if a lot of such enums required, code generation (e.g. T4) might be used.

提交回复
热议问题