如何在C#中枚举枚举?
例如,以下代码无法编译:
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
它给出了以下编译时错误:
“Suit”是“type”,但与“variable”类似
它在第二个Suit关键字上失败。
我想这对你有帮助。
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
}
在我看来,你真的想打印出每个枚举的名称,而不是值。在这种情况下,Enum.GetNames()似乎是正确的方法。
public enum Suits
{
Spades,
Hearts,
Clubs,
Diamonds,
NumSuits
}
public void PrintAllSuits()
{
foreach (string name in Enum.GetNames(typeof(Suits)))
{
System.Console.WriteLine(name);
}
}
顺便说一句,增加值不是枚举枚举值的好方法。你应该这样做。
我会改用Enum.GetValues(typeof(Suit))。
public enum Suits
{
Spades,
Hearts,
Clubs,
Diamonds,
NumSuits
}
public void PrintAllSuits()
{
foreach (var suit in Enum.GetValues(typeof(Suits)))
{
System.Console.WriteLine(suit.ToString());
}
}
我想这对你有帮助。
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
}