How to enumerate an enum

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

    There are two ways to iterate an Enum:

    1. var values =  Enum.GetValues(typeof(myenum))
    2. var values =  Enum.GetNames(typeof(myenum))
    

    The first will give you values in form on an array of **object**s, and the second will give you values in form of an array of **String**s.

    Use it in a foreach loop as below:

    foreach(var value in values)
    {
        // Do operations here
    }
    

提交回复
热议问题