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

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

提交回复
热议问题