întrebarea Asta are deja un raspuns aici: https://stackoverflow.com/questions/105372/how-to-enumerate-an-enum 26 răspunsuri
public enum Foos
{
A,
B,
C
}
Există o modalitate de a bucla prin valorile posibile ale Prosteste
?
Practic?
foreach(Foo in Foos)
Da, se poate folosi GetValues
metoda:
var values = Enum.GetValues(typeof(Foos));
Sau versiunea tastat:
var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
Am mult timp în urmă a adăugat un helper funcția de a mea bibliotecă privată pentru o astfel de ocazie:
public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
Utilizare:
var values = EnumUtil.GetValues<Foos>();
foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
Console.WriteLine(val);
}
Credit pentru Jon Skeet aici: http://bytes.com/groups/net-c/266447-how-loop-each-items-enum
foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
...
}
ACTUALIZARE De ceva timp, vad un comentariu care mă aduce înapoi la vechiul meu răspuns, și cred că m-am'd face diferit acum. Zilele astea m-am'd scrie:
private static IEnumerable<T> GetEnumValues<T>()
{
// Can't use type constraints on value types, so have to do check like this
if (typeof(T).BaseType != typeof(Enum))
{
throw new ArgumentException("T must be of type System.Enum");
}
return Enum.GetValues(typeof(T)).Cast<T>();
}
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
}