How to assign string values to enums and use that value in a switch

后端 未结 10 1648
小鲜肉
小鲜肉 2021-02-02 10:45

Basically a series of titles will be passed into the switch statement and I need to compare them against the string values of the enum. But I have little to no idea how to do th

相关标签:
10条回答
  • 2021-02-02 11:17

    Enum can only have integral underlying types (except char). Therefore you cannot do what you want, at least directly.

    However you can translate the string you have to the enum type:

    EnumType eVal = (EnumType)Enum.Parse(typeof(EnumType), strValue);
    
    switch(eVal)
    {
        case EnumType.doctor:/*...*/; break;
        case EnumType.mr: /*...*/; break;
    }
    
    0 讨论(0)
  • 2021-02-02 11:19

    This is not the kind of thing that should be hard-coded. It should be data-driven, possibly read from an external file or database. You could store them in a Dictionary and use the keys to drive your logic.

    0 讨论(0)
  • 2021-02-02 11:20

    I found that the best way for me to do this is by using the System.ComponentModel.DescriptionAttribute attribute on the enum values.

    Here is an example:

    using System.ComponentModel;
    
    public enum ActionCode
    {
        [Description("E")]
        Edit,
        [Description("D")]
        Delete,
        [Description("R")]
        Restore
    }
    

    Then, to use it, create an extension method on a static class like so:

    Edit: I rewrote the method to include a great suggestion from Laurie Dickinson so that the method returns the name of the enum value when there is no Description attribute. I also refactored the method to try to improve functionality. It now works for all Enums without using IConvertible.

    public static class Extensions
    {
        public static string GetDescription(this Enum e)
        {
            var attribute =
                e.GetType()
                    .GetTypeInfo()
                    .GetMember(e.ToString())
                    .FirstOrDefault(member => member.MemberType == MemberTypes.Field)
                    .GetCustomAttributes(typeof(DescriptionAttribute), false)
                    .SingleOrDefault()
                    as DescriptionAttribute;
    
            return attribute?.Description ?? e.ToString();
        }
    }
    

    So, to get the string associated with our enum above, we could use the following code:

    using Your.Extension.Method.Namespace;
    
    ...
    
    var action = ActionCode.Edit;
    var actionDescription = action.GetDescription();
    
    // Value of actionDescription will be "E".
    

    Here is another sample Enum:

    public enum TestEnum
    {
        [Description("This is test 1")]
        Test1,
        Test2,
        [Description("This is test 3")]
        Test3
    
    }
    

    Here is the code to see the description:

    var test = TestEnum.Test2;
    var testDescription = test.GetDescription();
    test = TestEnum.Test3;
    var testDescription2 = test.GetDescription();
    

    Results will be:

    testDescription: "Test2"
    testDescription2: "This is test 3"
    

    I wanted to go ahead and post the generic method as it is much more useful. It prevents you from having to write a custom extension for all of your enums.

    0 讨论(0)
  • 2021-02-02 11:22

    I wanted to add another answer for anyone using C# 6 or greater.

    If you are only wanting to get the name of the Enum value, you could use the new nameof() method introduced in C# 6.

    string enumName = nameof(MyEnum.EnumVal1); // enumName will equal "EnumVal1"
    

    While this may seem like overkill at first glance (why not just set the value of the string to "EnumVal1" to start with?), it will give you compile-time checking to make sure the value is valid. So, if you ever change the name of the enum value and forget to tell your IDE to find and replace all references, it will not compile until you fix them.

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