这个问题在这里已经有了答案: https://stackoverflow.com/questions/105372/how-to-enumerate-an-enum 26个答案。
public enum Foos
{
A,
B,
C
}
有没有办法循环浏览Foos
的可能值?
基本上?
foreach(Foo in Foos)
是的,你可以使用GetValues
方法。
var values = Enum.GetValues(typeof(Foos));
或者打字版本。
var values = Enum.GetValues(typeof(Foos)).Cast<Foos>();
很久以前,我在我的私人库中添加了一个辅助函数,就是为了应对这种情况。
public static class EnumUtil {
public static IEnumerable<T> GetValues<T>() {
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
使用方法。
var values = EnumUtil.GetValues<Foos>();
foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
Console.WriteLine(val);
}
这里有乔恩-斯基特的功劳。 http://bytes.com/groups/net-c/266447-how-loop-each-items-enum
foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
...
}
已更新 一段时间以来,我看到一个评论,让我想起了我以前的回答,我想我'现在会用不同的方式来回答。 这些天我'会写。
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
}