如何在C#中枚举枚举?

例如,以下代码无法编译:

public enum Suit
{
    Spades,
    Hearts,
    Clubs,
    Diamonds
}

public void EnumerateAllSuitsDemoMethod()
{
    foreach (Suit suit in Suit)
    {
        DoSomething(suit);
    }
}

它给出了以下编译时错误:

“Suit”是“type”,但与“variable”类似

它在第二个Suit关键字上失败。


当前回答

新的.NET 5解决方案:

.NET 5为GetValues方法引入了新的通用版本:

Suit[] suitValues = Enum.GetValues<Suit>();

这是目前为止最方便的方法。

foreach循环中的用法:

foreach (Suit suit in Enum.GetValues<Suit>())
{

}

如果您只需要枚举名作为字符串,则可以使用通用的GetNames方法:

string[] suitNames = Enum.GetNames<Suit>();

其他回答

LINQ通用方式:

    public static Dictionary<int, string> ToList<T>() where T : struct =>
        ((IEnumerable<T>)Enum.GetValues(typeof(T))).ToDictionary(value => Convert.ToInt32(value), value => value.ToString());

用法:

        var enums = ToList<Enum>();

我想你可以用

Enum.GetNames(Suit)

某些版本的.NET框架不支持Enum.GetValues。以下是Ideas 2.0的一个很好的解决方法:Compact framework中的Enum.Get Values:

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

与任何涉及反射的代码一样,您应该采取措施确保它只运行一次并缓存结果。

foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
}

(目前公认的答案有一个我不认为的演员阵容需要(尽管我可能错了)。)

将枚举转换为可以交互的对象的简单通用方法:

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

然后:

var enums = EnumHelper.ToList<MyEnum>();