如何在C#中枚举枚举?

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

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

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

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

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

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


当前回答

我使用ToString(),然后拆分并解析flags中的spit数组。

[Flags]
public enum ABC {
   a = 1,
   b = 2,
   c = 4
};

public IEnumerable<ABC> Getselected (ABC flags)
{
   var values = flags.ToString().Split(',');
   var enums = values.Select(x => (ABC)Enum.Parse(typeof(ABC), x.Trim()));
   return enums;
}

ABC temp= ABC.a | ABC.b;
var list = getSelected (temp);
foreach (var item in list)
{
   Console.WriteLine(item.ToString() + " ID=" + (int)item);
}

其他回答

我想你可以用

Enum.GetNames(Suit)

如果您有:

enum Suit
{
   Spades,
   Hearts,
   Clubs,
   Diamonds
}

这:

foreach (var e in Enum.GetValues(typeof(Suit)))
{
    Console.WriteLine(e.ToString() + " = " + (int)e);
}

将输出:

Spades = 0
Hearts = 1
Clubs = 2
Diamonds = 3

在Silverlight中无法获取Enum.GetValues()。

Einar Ingebrigitsen原创博客:

public class EnumHelper
{
    public static T[] GetValues<T>()
    {
        Type enumType = typeof(T);

        if (!enumType.IsEnum)
        {
            throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
        }

        List<T> values = new List<T>();

        var fields = from field in enumType.GetFields()
                     where field.IsLiteral
                     select field;

        foreach (FieldInfo field in fields)
        {
            object value = field.GetValue(enumType);
            values.Add((T)value);
        }

        return values.ToArray();
    }

    public static object[] GetValues(Type enumType)
    {
        if (!enumType.IsEnum)
        {
            throw new ArgumentException("Type '" + enumType.Name + "' is not an enum");
        }

        List<object> values = new List<object>();

        var fields = from field in enumType.GetFields()
                     where field.IsLiteral
                     select field;

        foreach (FieldInfo field in fields)
        {
            object value = field.GetValue(enumType);
            values.Add(value);
        }

        return values.ToArray();
    }
}

我知道这有点乱,但如果你喜欢一句话,这里有一句:

((Suit[])Enum.GetValues(typeof(Suit))).ToList().ForEach(i => DoSomething(i));

我想这对你有帮助。

public class Program
{

    public static List<T> GetEnamList<T>()
    {
        var enums = Enum.GetValues(typeof(T)).Cast<T>().Select(v => v).ToList();
        return enums;
    }
    private void LoadEnumList()
    {
        List<DayofWeek> dayofweeks = GetEnamList<DayofWeek>();

        foreach (var item in dayofweeks)
        {
            dayofweeks.Add(item);
        }
    }
}

    public enum DayofWeek
    {
        Monday,
        Tuesday,
        Wensday,
        Thursday,
        Friday,
        Sturday,
        Sunday
    }