I have a public enum
declared like this:
public enum States
{
SomeState,
SomeOtherState
}
Having an arbitrary string myString
which may represent any of the "States" above, I'd like to write a switch to check which one it currently is.
This is my attempt.
States state = Enum.Parse(States, myString, true);
switch (state)
{
case States.SomeState:
case States.SomeOtherState:
break;
default:
break;
}
Inside of the Enum.Parse()
it tells me that the argument State is being used as a type instead that as a variable. Isn't that the correct usage? The first argument Enum.Parse is supposed to receive is Type enumType
: why then it tells me it needs a variable?
Many kind replies indicates to use typeof
. Unfortunately, I've already tried that but since I receive the following error I guessed it was a wrong idea.
Enum.Parse(typeof(States), myString, true);
yields:
cannot implicitly convert type 'object' to 'States'. An explicit conversion exists.
Yes, you need to send in the Type of enum that your are parsing into (using typeof
):
States state = (States)Enum.Parse(typeof(States), myString, true);
The Parse
method is expecting an argument of type System.Type
. Not the type States
.
Here is the signature from the docs .
[ComVisibleAttribute(true)]
public static Object Parse(
Type enumType,
string value,
bool ignoreCase
)
Parse
returns an object
so it requires you to cast to your type after the parse.
Since it is expecting a type, change Enum.Parse(States, myString, true)
; to Enum.Parse(typeof(States), myString, true);
This is the correct one.
States state = Enum.Parse(typeof(States), myString, true);
switch (state)
{
case States.SomeState:
case States.SomeOtherState:
break;
default:
break;
}
States tmp;
Enum.TryParse<States>(myString,true ,out tmp);
Can Make it more elegant by using extension class
like so:
namespace YourClass.Models;
public static class Converters
{
public static T ConvertToEnum<T>(this string value) where T : Enum
=> (T)Enum.Parse(typeof(T), value);
}
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.