How to enumerate an enum

后端 未结 29 1898
深忆病人
深忆病人 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:30

    foreach (Suit suit in Enum.GetValues(typeof(Suit))) { }
    

    I've heard vague rumours that this is terifically slow. Anyone know? – Orion Edwards Oct 15 '08 at 1:31 7

    I think caching the array would speed it up considerably. It looks like you're getting a new array (through reflection) every time. Rather:

    Array enums = Enum.GetValues(typeof(Suit));
    foreach (Suit suitEnum in enums) 
    {
        DoSomething(suitEnum);
    }
    

    That's at least a little faster, ja?

提交回复
热议问题