How to enumerate an enum

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

    Some versions of the .NET framework do not support Enum.GetValues. Here's a good workaround from Ideas 2.0: Enum.GetValues in Compact Framework:

    public Enum[] GetValues(Enum enumeration)
    {
        FieldInfo[] fields = enumeration.GetType().GetFields(BindingFlags.Static | BindingFlags.Public);
        Enum[] enumerations = new Enum[fields.Length];
    
        for (var i = 0; i < fields.Length; i++)
            enumerations[i] = (Enum) fields[i].GetValue(enumeration);
    
        return enumerations;
    }
    

    As with any code that involves reflection, you should take steps to ensure it runs only once and results are cached.

提交回复
热议问题