【发布时间】:2010-11-01 14:52:54
【问题描述】:
这个问题在这里已经有了答案:
How do I enumerate an enum in C#? 26 个答案
public enum Foos
{
A,
B,
C
}
有没有办法循环遍历Foos 的可能值?
基本上?
foreach(Foo in Foos)
【问题讨论】:
标签: c# .net enums language-features
这个问题在这里已经有了答案:
How do I enumerate an enum in C#? 26 个答案
public enum Foos
{
A,
B,
C
}
有没有办法循环遍历Foos 的可能值?
基本上?
foreach(Foo in Foos)
【问题讨论】:
标签: c# .net enums language-features
是的,您可以使用 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>();
【讨论】:
(T[])Enum.GetValues(typeof(T))
.Cast<Foos>),并且 (2) 您不需要将所有值并再次拆箱。只要不将返回的数组类型更改为其他类型(如object[]),Şafak 的强制转换将保持有效。但我们可以完全确定它们不会,因为 (a) 它会失去性能,(b) 已经有数百万条代码行使用 Şafak 的演员表,它们都会因运行时异常而中断。
public static IReadOnlyList<T> GetValues<T>() { return (T[])Enum.GetValues(typeof(T)); }。但是,是的,在常见用法中性能差异可以忽略不计。当我已经有一个可迭代(可枚举)对象要返回时,我只是不喜欢创建迭代器的想法。
是的。在System.Enum 类中使用GetValues() 方法。
【讨论】:
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
}
【讨论】:
更新
一段时间后,我看到一条评论让我回到原来的答案,我想我现在会采取不同的做法。这些天我会写:
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>();
}
【讨论】:
You can cast the array directly: (T[])Enum.GetValues(typeof(T))@SafakGür,这个版本的 IMO 开销更少。
Constraint cannot be special class 'Enum'
Enum(以及 unmanaged 和 delegate)作为通用约束。
foreach(Foos foo in Enum.GetValues(typeof(Foos)))
【讨论】:
Foos,没有任何东西可以神奇地推断出来。这是一个明确的演员表。
foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
...
}
【讨论】:
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
【讨论】: