如何遍历 C# 中的所有枚举值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/972307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through all enum values in C#?
提问by divinci
This question already has an answer here:
How do I enumerate an enum in C#?26 answers
这个问题在这里已经有了答案:
How do I enumerate an enum in C#? 26 个回答
public enum Foos
{
A,
B,
C
}
Is there a way to loop through the possible values of Foos
?
有没有办法循环遍历 的可能值Foos
?
Basically?
基本上?
foreach(Foo in Foos)
采纳答案by JaredPar
Yes you can use the ?GetValue???s
method:
是的,您可以使用 ? GetValue???s
方法:
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>();
回答by SLaks
foreach(Foos foo in Enum.GetValues(typeof(Foos)))
回答by Pablo Santa Cruz
Yes. Use GetValues()
method in System.Enum
class.
是的。GetValues()
在System.Enum
课堂上使用方法。
回答by Inisheer
foreach (EMyEnum val in Enum.GetValues(typeof(EMyEnum)))
{
Console.WriteLine(val);
}
Credit to Jon Skeet here: http://bytes.com/groups/net-c/266447-how-loop-each-items-enum
归功于 Jon Skeet:http: //bytes.com/groups/net-c/266447-how-loop-each-items-enum
回答by adrianbanks
foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
...
}
回答by Vasu Balakrishnan
Enum.GetValues(typeof(Foos))
回答by Neil Barnwell
UPDATED
Some time on, I see a comment that brings me back to my old answer, and I think I'd do it differently now. These days I'd write:
更新了
一段时间,我看到一条评论让我回到了我的旧答案,我想我现在会做不同的事情。这几天我会写:
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>();
}
回答by dbones
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
}