String representation of an Enum

后端 未结 30 1929
不思量自难忘°
不思量自难忘° 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<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>();
      
      • 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();
      }
      
    0 讨论(0)
  • 2020-11-22 03:26

    for me, the pragmatic approach is class inside class, sample:

    public class MSEModel
    {
        class WITS
        {
            public const string DATE = "5005";
            public const string TIME = "5006";
            public const string MD = "5008";
            public const string ROP = "5075";
            public const string WOB = "5073";
            public const string RPM = "7001";
    ... 
        }
    
    0 讨论(0)
  • 2020-11-22 03:26

    Here is yet another way to accomplish the task of associating strings with enums:

    struct DATABASE {
        public enum enums {NOTCONNECTED, CONNECTED, ERROR}
        static List<string> strings =
            new List<string>() {"Not Connected", "Connected", "Error"};
    
        public string GetString(DATABASE.enums value) {
            return strings[(int)value];
        }
    }
    

    This method is called like this:

    public FormMain() {
        DATABASE dbEnum;
    
        string enumName = dbEnum.GetString(DATABASE.enums.NOTCONNECTED);
    }
    

    You can group related enums in their own struct. Since this method uses the enum type, you can use Intellisense to display the list of enums when making the GetString() call.

    You can optionally use the new operator on the DATABASE struct. Not using it means the strings List is not allocated until the first GetString() call is made.

    0 讨论(0)
  • 2020-11-22 03:27

    I really like Jakub Šturc's answer, but it's shortcoming is that you cannot use it with a switch-case statement. Here's a slightly modified version of his answer that can be used with a switch statement:

    public sealed class AuthenticationMethod
    {
        #region This code never needs to change.
        private readonly string _name;
        public readonly Values Value;
    
        private AuthenticationMethod(Values value, String name){
            this._name = name;
            this.Value = value;
        }
    
        public override String ToString(){
            return _name;
        }
        #endregion
    
        public enum Values
        {
            Forms = 1,
            Windows = 2,
            SSN = 3
        }
    
        public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (Values.Forms, "FORMS");
        public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (Values.Windows, "WINDOWS");
        public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (Values.SSN, "SSN");
    }
    

    So you get all of the benefits of Jakub Šturc's answer, plus we can use it with a switch statement like so:

    var authenticationMethodVariable = AuthenticationMethod.FORMS;  // Set the "enum" value we want to use.
    var methodName = authenticationMethodVariable.ToString();       // Get the user-friendly "name" of the "enum" value.
    
    // Perform logic based on which "enum" value was chosen.
    switch (authenticationMethodVariable.Value)
    {
        case authenticationMethodVariable.Values.Forms: // Do something
            break;
        case authenticationMethodVariable.Values.Windows: // Do something
            break;
        case authenticationMethodVariable.Values.SSN: // Do something
            break;      
    }
    
    0 讨论(0)
  • 2020-11-22 03:27

    If you've come here looking to implement a simple "Enum" but whose values are strings instead of ints, here is the simplest solution:

        public sealed class MetricValueList
        {
            public static readonly string Brand = "A4082457-D467-E111-98DC-0026B9010912";
            public static readonly string Name = "B5B5E167-D467-E111-98DC-0026B9010912";
        }
    

    Implementation:

    var someStringVariable = MetricValueList.Brand;
    
    0 讨论(0)
  • 2020-11-22 03:27

    I wanted to post this as a comment to the post quoted below but couldn't because I don't have enough rep - so please don't down-vote. The code contained an error and I wanted to point this out to individuals trying to use this solution:

    [TypeConverter(typeof(CustomEnumTypeConverter(typeof(MyEnum))]
    public enum MyEnum
    {
      // The custom type converter will use the description attribute
      [Description("A custom description")]
      ValueWithCustomDescription,
      // This will be exposed exactly.
      Exact
    }
    

    should be

    [TypeConverter(typeof(CustomEnumTypeConverter<MyEnum>))]
    public enum MyEnum
    {
      // The custom type converter will use the description attribute
      [Description("A custom description")]
      ValueWithCustomDescription,
    
      // This will be exposed exactly.
      Exact
    }
    

    Brillant!

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