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

后端 未结 10 1647
小鲜肉
小鲜肉 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 10:58

    Have a read of this tutorial to understand how enums work. There are examples of switch statements too.

    0 讨论(0)
  • 2021-02-02 10:59

    Enumerations cannot be of string type.

    The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

    http://msdn.microsoft.com/en-us/library/sbbt4032.aspx

    0 讨论(0)
  • 2021-02-02 10:59

    Just sharing my solution. By downloading the nuget package Extension.MV, a method is available for getting the string from a Enum Description

    public enum Prefix
    {
        [Description("doctor")]
        doctor = 1,
        [Description("mr")]
        mr = 2,
        [Description("mrs")]
        mrs = 3
    }
    
    public static class PrefixAdapter {
    
        public static string ToText(this Prefix prefix) {
            return prefix.GetEnumDescription();
        }
    
        public static Prefix ToPrefix(this string text) {
            switch (text)
            {
                case "doctor"
                    return Prefix.doctor;
                case "mr"
                    return Prefix.mr;
                case "ms"
                    return Prefix.mrs;
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-02 11:08

    You can't have an enum with an underlying type of string. The underlying type can be any integral type except char.

    If you want to translate a string to your enum then you'll probably need to use the Parse or TryParse methods.

    string incoming = "doctor";
    
    // throws an exception if the string can't be parsed as a TestEnum
    TestEnum foo = (TestEnum)Enum.Parse(typeof(TestEnum), incoming, true);
    
    // try to parse the string as a TestEnum without throwing an exception
    TestEnum bar;
    if (Enum.TryParse(incoming, true, out bar))
    {
        // success
    }
    else
    {
        // the string isn't an element of TestEnum
    }
    
    // ...
    
    enum TestEnum
    {
        Doctor, Mr, Mrs
    }
    
    0 讨论(0)
  • 2021-02-02 11:10

    Why not to use just pure enum and switches?

    enum Prefix
    {
        doctor,
        mr,
        mrs
    }
    

    Then you can use is like

    string case = "doctor";
    
    switch ((Prefix)Enum.Parse(typeof(Prefix), "doctor"))
    {
        case Prefix.doctor:
            ...
            break;
        ...
        default:
            break;
    }
    
    0 讨论(0)
  • 2021-02-02 11:14

    I believe the standard way to do this is to use a static class with readonly string properties that return the value you want.

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