How do I enumerate an enum in C#?

2018-12-31 04:41发布

How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit 
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod() 
{
    foreach (Suit suit in Suit) 
    {
        DoSomething(suit);
    }
}

And gives the following compile-time error:

'Suit' is a 'type' but is used like a 'variable'

It fails on the Suit keyword, the second one.

26条回答
闭嘴吧你
2楼-- · 2018-12-31 05:04
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}
查看更多
倾城一夜雪
3楼-- · 2018-12-31 05:05

I think this is more efficient than other suggestions because GetValues() is not called each time you have a loop. It is also more concise. And you get a compile-time error not a runtime exception if Suit is not an enum.

EnumLoop<Suit>.ForEach((suit) => {
    DoSomethingWith(suit);
});

EnumLoop has this completely generic definition:

class EnumLoop<Key> where Key : struct, IConvertible {
    static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
    static internal void ForEach(Action<Key> act) {
        for (int i = 0; i < arr.Length; i++) {
            act(arr[i]);
        }
    }
}
查看更多
裙下三千臣
4楼-- · 2018-12-31 05:05

I know it is a bit messy but if you are fan of one-liners, here is one:

((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));
查看更多
无与为乐者.
5楼-- · 2018-12-31 05:05

Also you can bind to the public static members of the enum directly by using reflection:

typeof(Suit).GetMembers(BindingFlags.Public | BindingFlags.Static)
    .ToList().ForEach(x => DoSomething(x.Name));
查看更多
余生请多指教
6楼-- · 2018-12-31 05:06

It looks to me like you really want to print out the names of each enum, rather than the values. In which case Enum.GetNames() seems to be the right approach.

public enum Suits
{
    Spades,
    Hearts,
    Clubs,
    Diamonds,
    NumSuits
}

public void PrintAllSuits()
{
    foreach (string name in Enum.GetNames(typeof(Suits)))
    {
        System.Console.WriteLine(name);
    }
}

By the way, incrementing the value is not a good way to enumerate the values of an enum. You should do this instead.

I would use Enum.GetValues(typeof(Suit)) instead.

public enum Suits
{
    Spades,
    Hearts,
    Clubs,
    Diamonds,
    NumSuits
}

public void PrintAllSuits()
{
    foreach (var suit in Enum.GetValues(typeof(Suits)))
    {
        System.Console.WriteLine(suit.ToString());
    }
}
查看更多
倾城一夜雪
7楼-- · 2018-12-31 05:06
foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
}

(The current accepted answer has a cast that I don't think is needed (although I may be wrong).)

查看更多
登录 后发表回答