¿Cómo se puede convertir un int
en un enum
en C#?
De una cadena:
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.")
A partir de un int:
YourEnum foo = (YourEnum)yourInt;
Actualización:
Desde el número también se puede
YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);
Sólo lánzalo:
MyEnum e = (MyEnum)3;
Puedes comprobar si está en el rango usando Enum.IsDefined:
if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }
Tomemos el siguiente ejemplo:
int one = 1;
MyEnum e = (MyEnum)one;