如何在C#中枚举枚举?

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

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

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

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

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

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


当前回答

foreach(Enum.GetValues中的套装(typeof(套装))){}我听到一些模糊的谣言,说这是非常缓慢。有人知道吗猎户座Edwards 2008年10月15日1:31 7

我认为缓存阵列会大大加快速度。看起来每次都会得到一个新的数组(通过反射)。相反:

Array enums = Enum.GetValues(typeof(Suit));
foreach (Suit suitEnum in enums) 
{
    DoSomething(suitEnum);
}

这至少快一点,对吧?

其他回答

我想你可以用

Enum.GetNames(Suit)

三种方式:

Enum.GetValues(类型)//自.NET 1.1起,不在Silverlight或.NET Compact Framework中type.GetEnumValues()//仅适用于.NET 4及更高版本type.GetFields()。其中(x=>x.IsLiteral)。Select(x=>x.GetValue(null))//在任何地方都有效

我不确定为什么在类型实例上引入GetEnumValues。对我来说,它一点也不可读。


拥有Enum<T>这样的助手类对我来说是最可读和难忘的:

public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
    public static IEnumerable<T> GetValues()
    {
        return (T[])Enum.GetValues(typeof(T));
    }

    public static IEnumerable<string> GetNames()
    {
        return Enum.GetNames(typeof(T));
    }
}

现在您拨打:

Enum<Suit>.GetValues();

// Or
Enum.GetValues(typeof(Suit)); // Pretty consistent style

如果性能很重要,也可以使用某种缓存,但我不认为这是一个问题。

public static class Enum<T> where T : struct, IComparable, IFormattable, IConvertible
{
    // Lazily loaded
    static T[] values;
    static string[] names;

    public static IEnumerable<T> GetValues()
    {
        return values ?? (values = (T[])Enum.GetValues(typeof(T)));
    }

    public static IEnumerable<string> GetNames()
    {
        return names ?? (names = Enum.GetNames(typeof(T)));
    }
}

将方法public static IEnumerable<T>GetValues<T>()添加到类中,如:

public static IEnumerable<T> GetValues<T>()
{
    return Enum.GetValues(typeof(T)).Cast<T>();
}

调用并传递枚举。现在您可以使用foreach遍历它:

 public static void EnumerateAllSuitsDemoMethod()
 {
     // Custom method
     var foos = GetValues<Suit>();
     foreach (var foo in foos)
     {
         // Do something
     }
 }

下面是一个为DDL创建选择选项的工作示例:

var resman = ViewModelResources.TimeFrame.ResourceManager;

ViewBag.TimeFrames = from MapOverlayTimeFrames timeFrame
      in Enum.GetValues(typeof(MapOverlayTimeFrames))
      select new SelectListItem
      {
         Value = timeFrame.ToString(),
         Text = resman.GetString(timeFrame.ToString()) ?? timeFrame.ToString()
      };

此外,还可以使用反射直接绑定到枚举的公共静态成员:

typeof(Suit).GetMembers(BindingFlags.Public | BindingFlags.Static)
    .ToList().ForEach(x => DoSomething(x.Name));