Casting an integer value to an enum type is easy enough using the cast operator:
class MainClass {
public enum Suit {
Hearts = 0,
Diamonds = 1,
Clubs = 2,
Spades = 3
}
public static void Main(string[] args) {
// Cast int to enum type using explicit type
object mySuit = (Suit)2;
Console.WriteLine(mySuit);
}
}
But suppose I have a Type
object representing a enum type. How can I cast an integer value to a equivalent enum using reflection?
public static void Main() {
// Cast int to enum type using reflection
object myEnum = CastIntToEnum(typeof(Suit), 3);
Console.WriteLine(myEnum);
}
static object CastIntToEnum(Type enumType, int i)
{
//?
}
Aucun commentaire:
Enregistrer un commentaire