简体   繁体   中英

Convert string to enum in a function

I have a method which takes in two enums and returns a bool[] . However, in practice I have a string that I want to pass it, by converting it to an enum.

I have the following code:

    path = StatePath.statePath(Enum.GetName(typeof(StatePath.States), currentState), (Enum.GetName(typeof(StatePath.States), stable_state_ENDDR));

Here, currentState and stable_state_ENDDR are strings that I retrieve from some other code. The values of those strings match enums in the States enum. The code throws an error, saying that I can't convert from string to enum. I have tried several of the examples I found on StackOverflow and Google alike, but none of the solutions worked. What to do?

Call Enum.Parse and cast the return value to your enum type, eg:

string currentState = "...";
States states = (StatePath.States)Enum.Parse(typeof(StatePath.States), currentState);

There is a TryParse overload as well:

if (Enum.TryParse(typeof(StatePath.States), currentState, out object o))
    StatePath.States states = (StatePath.States)o;

...and a generic version that saves you from having to cast the value explicitly yourself:

if (Enum.TryParse(currentState, out StatePath.States state))

Without knowing the signature of the function, this is quite difficult to answer, but I think you are looking for Enum.TryParse : Declare the enums eCurrentState and eStable_state_ENDDR , then use

Enum.TryParse(currentState, out eCurrentState);

Enum.TryParse(stable_state_ENDDR, out eStable_state_ENDDR);

path = StatePath.statePath(eCurrentState, eStable_state_ENDDR);

If the TryParse fails, it returns false .

That being said, a general rule of thumb is to avoid scenarios like these and pass enums as int or bit flags , this is because internally thats how enums are stored, and require no conversion function to slow you down. Basically, SomeEnum == someIntValue would work directly without any conversion. So assuming you are getting your data from some server/db, simply request the data as a numeric value equal to the index of the enum that it is declared in . Conversely, store the data in the same way.

eg with any enum, with no attributes declared

enum SomeEnum
{
    abc, // 0
    def, // 1
    g    // 2
}

abc == 0 , def == 1 , g == 2 , would return true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM