String representation of an Enum

后端 未结 30 2330
不思量自难忘°
不思量自难忘° 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:24

    Try type-safe-enum pattern.

    public sealed class AuthenticationMethod {
    
        private readonly String name;
        private readonly int value;
    
        public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS");
        public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (2, "WINDOWS");
        public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (3, "SSN");        
    
        private AuthenticationMethod(int value, String name){
            this.name = name;
            this.value = value;
        }
    
        public override String ToString(){
            return name;
        }
    
    }
    

    Update Explicit (or implicit) type conversion can be done by

    • adding static field with mapping

      private static readonly Dictionary instance = new Dictionary();
      
      • n.b. In order that the initialisation of the the "enum member" fields doesn't throw a NullReferenceException when calling the instance constructor, be sure to put the Dictionary field before the "enum member" fields in your class. This is because static field initialisers are called in declaration order, and before the static constructor, creating the weird and necessary but confusing situation that the instance constructor can be called before all static fields have been initialised, and before the static constructor is called.
    • filling this mapping in instance constructor

      instance[name] = this;
      
    • and adding user-defined type conversion operator

      public static explicit operator AuthenticationMethod(string str)
      {
          AuthenticationMethod result;
          if (instance.TryGetValue(str, out result))
              return result;
          else
              throw new InvalidCastException();
      }
      

提交回复
热议问题