Can you loop through all enum values?
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<Foos>();
I long ago added a helper function to my private library for just such an occasion:
public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
Usage:
var values = EnumUtil.GetValues<Foos>();
foreach(Foos foo in Enum.GetValues(typeof(Foos)))
foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
Console.WriteLine(val);
}
感谢Jon Skeet:http://bytes.com/groups/net-c/266447-how-loop-each-items-enum
链接地址: http://www.djcxy.com/p/2664.html上一篇: 我如何在Python中表示'Enum'?
下一篇: 你可以遍历所有的枚举值?