Comment convertir une string en une enum ?
Une petite astuce qui vient de me depanner à l'instant
Merci Tim Sneath
C# : object Enum.Parse(System.Type enumType, string value, bool ignoreCase);
VB.NET : object [Enum].Parse(System.Type enumType, string value, bool ignoreCase)
Comme je suis bien sympa, voici des petits exemples en VB et en C#
enum Colour
{
Yellow,
Green,
Blue
}
// ...
Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true);
Console.WriteLine("Colour Value: {0}", c.ToString());
// Picking an invalid colour throws an ArgumentException. To
// avoid this, call Enum.IsDefined() first, as follows:
string nonColour = "Polkadot";
if (Enum.IsDefined(typeof(Colour), nonColour))
c = (Colour) Enum.Parse(typeof(Colour), nonColour, true);
else
MessageBox.Show("KCCCCC!");
Enum Colour
Yellow
Green
Blue
End Enum
' ...
Dim c As Colour = CType([Enum].Parse(GetType(Colour), "Red", True), Colour)
Console.WriteLine("Colour Value: {0}", c.ToString())
' Picking an invalid colour throws an ArgumentException. To
' avoid this, call Enum.IsDefined() first, as follows:
Dim nonColour As String = "Polkadot"
If [Enum].IsDefined(GetType(Colour), nonColour) Then
c = CType([Enum].Parse(GetType(Colour), nonColour, True), Colour)
Else
MessageBox.Show("KCCCCC!")
End If
Ce post vous a plu ? Ajoutez le dans vos favoris pour ne pas perdre de temps à le retrouver le jour où vous en aurez besoin :