How to enumerate an enum

后端 未结 29 1901
深忆病人
深忆病人 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条回答
  •  旧时难觅i
    2020-11-22 01:48

    I do not hold the opinion this is better, or even good. I am just stating yet another solution.

    If enum values range strictly from 0 to n - 1, a generic alternative is:

    public void EnumerateEnum()
    {
        int length = Enum.GetValues(typeof(T)).Length;
        for (var i = 0; i < length; i++)
        {
            var @enum = (T)(object)i;
        }
    }
    

    If enum values are contiguous and you can provide the first and last element of the enum, then:

    public void EnumerateEnum()
    {
        for (var i = Suit.Spade; i <= Suit.Diamond; i++)
        {
            var @enum = i;
        }
    }
    

    But that's not strictly enumerating, just looping. The second method is much faster than any other approach though...

提交回复
热议问题