如何遍历C#中的所有枚举值? [重复]

问题描述 投票:1264回答:8

这个问题在这里已有答案: 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
8个回答
1866
投票

是的你可以使用GetValue‍‍‍s方法:

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>();

753
投票
foreach(Foos foo in Enum.GetValues(typeof(Foos)))

115
投票
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


57
投票
foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
    ...
}

34
投票

更新 一段时间后,我看到一条评论让我回到原来的答案,我想我现在会采用不同的方式。这些天我写道:

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>();
}

24
投票
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
}

9
投票
 Enum.GetValues(typeof(Foos))

6
投票

是。在GetValues()类中使用System.Enum方法。

© www.soinside.com 2019 - 2024. All rights reserved.