tutorial - example enum c#
Come scorrere tutti i valori enum in C#? (6)
Questa domanda ha già una risposta qui:
Come faccio a enumerare un enum in C #? 26 risposte
public enum Foos
{
A,
B,
C
}
C'è un modo per scorrere i possibili valori di Foos
?
Fondamentalmente?
foreach(Foo in Foos)
Sì, puoi utilizzare il metodo GetValues
:
var values = Enum.GetValues(typeof(Foos));
Oppure la versione digitata:
var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
Molto tempo fa ho aggiunto una funzione di supporto alla mia biblioteca privata proprio per un'occasione del genere:
public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
Uso:
var values = EnumUtil.GetValues<Foos>();
Sì. Utilizzare il metodo GetValues()
nella classe System.Enum
.
Enum.GetValues(typeof(Foos))
foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
Console.WriteLine(val);
}
Credito a Jon Skeet qui: http://bytes.com/groups/net-c/266447-how-loop-each-items-enum
foreach(Foos foo in Enum.GetValues(typeof(Foos)))
static void Main(string[] args)
{
foreach (int value in Enum.GetValues(typeof(DaysOfWeek)))
{
Console.WriteLine(((DaysOfWeek)value).ToString());
}
foreach (string value in Enum.GetNames(typeof(DaysOfWeek)))
{
Console.WriteLine(value);
}
Console.ReadLine();
}
public enum DaysOfWeek
{
monday,
tuesday,
wednesday
}