Cette question a déjà une réponse ici: https://stackoverflow.com/questions/105372/how-to-enumerate-an-enum 26 réponses
<-- Fin du texte inséré automatiquement -->
public enum Foos
{
A,
B,
C
}
Existe-t-il un moyen de parcourir en boucle les valeurs possibles de Foos
?
En gros ?
foreach(Foo in Foos)
Oui, vous pouvez utiliser la méthode [GetValues
][1] :
var values = Enum.GetValues(typeof(Foos));
Ou la version typée :
var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
Il y a longtemps que j'ai ajouté une fonction d'aide à ma bibliothèque privée pour une telle occasion :
public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
Utilisation :
var values = EnumUtil.GetValues<Foos>();
[1] : https://docs.microsoft.com/en-us/dotnet/api/system.enum.getvalues
Oui. Utilisez la méthode [GetValues()
][1] de la classe [System.Enum
][2].
[1] : https://msdn.microsoft.com/en-us/library/system.enum.getvalues.aspx [2] : http://msdn.microsoft.com/en-us/library/system.enum.aspx