How to enumerate an enum

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

    A simple and generic way to convert an enum to something you can interact:

    public static Dictionary ToList() where T : struct
    {
       return ((IEnumerable)Enum
           .GetValues(typeof(T)))
           .ToDictionary(
               item => Convert.ToInt32(item),
               item => item.ToString());
    }
    

    And then:

    var enums = EnumHelper.ToList();
    

提交回复
热议问题