How to enumerate an enum

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

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

提交回复
热议问题