Comment convertir un int en enum en C# ?
A partir d’un int :
YourEnum foo = (YourEnum)yourInt;
A partir d’une chaine :
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
// La verification foo.ToString().Contains(",") est necessaire pour
// les enumerations marquees avec un attribut [Flags].
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
throw new InvalidOperationException(
$"{yourString} is not an underlying value of the YourEnum enumeration."
);
}
Dynamiquement (type inconnu a la compilation) :
Type enumType = ...;
// NB : Les enums peuvent specifier un type de base autre que 'int'
int numericValue = ...;
object boxedEnumValue = Enum.ToObject(enumType, numericValue);