How to enumerate an enum

后端 未结 29 1832
深忆病人
深忆病人 2020-11-22 01:14

How can you enumerate an enum in C#?

E.g. the following code does not compile:

public enum Suit
{         


        
29条回答
  •  灰色年华
    2020-11-22 01:43

    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.ForEach((suit) => {
        DoSomethingWith(suit);
    });
    

    EnumLoop has this completely generic definition:

    class EnumLoop where Key : struct, IConvertible {
        static readonly Key[] arr = (Key[])Enum.GetValues(typeof(Key));
        static internal void ForEach(Action act) {
            for (int i = 0; i < arr.Length; i++) {
                act(arr[i]);
            }
        }
    }
    

提交回复
热议问题