UPDATED 一段时间后,我看到一条评论让我回到原来的答案,我想我写的是:'d do it differently now. These days I':
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>();
}
101
foreach(Foos foo in Enum.GetValues(typeof(Foos)))
48
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
}
7
foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
...
}
8 回答
UPDATED
一段时间后,我看到一条评论让我回到原来的答案,我想我写的是:'d do it differently now. These days I':
是 . 在System.Enum类中使用GetValues()方法 .
是的,您可以使用
GetValues
方法:或者键入的版本:
我很久以前就在这样的场合为我的私人图书馆添加了一个辅助函数:
用法:
感谢Jon Skeet:http://bytes.com/groups/net-c/266447-how-loop-each-items-enum