Wie kann in C# ein "int" in ein "enum" umgewandelt werden?
Aus einer Zeichenkette:
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
// the foo.ToString().Contains(",") check is necessary for enumerations marked with an [Flags] attribute
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
throw new InvalidOperationException($"{yourString} is not an underlying value of the YourEnum enumeration.")
Aus einer int:
YourEnum foo = (YourEnum)yourInt;
Aktualisierung:
Von Nummer können Sie auch
YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);
Werfen Sie es einfach:
MyEnum e = (MyEnum)3;
Mit Enum.IsDefined können Sie prüfen, ob der Wert im Bereich liegt:
if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }
Nehmen Sie das folgende Beispiel:
int one = 1;
MyEnum e = (MyEnum)one;