This question already has an answer here:
How to enumerate an enum? 14 answers
public enum Foos
{
A,
B,
C
}
Is there a way to loop through the possible values of Foos?
Basically?
foreach(Foo in Foos)
解决方案
Yes you can use the GetValues method
var values = Enum.GetValues(typeof(Foos));
Or the typed version
var values = Enum.GetValues(typeof(Foos)).Cast();
I long ago added a helper function to my private library for just such an occasion
public static class EnumUtil {
public static IEnumerable GetValues() {
return Enum.GetValues(typeof(T)).Cast();
}
}
Usage:
var values = EnumUtil.GetValues();