如何枚举一个枚举 [英] How to enumerate an enum
本文介绍了如何枚举一个枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 C# 中枚举 enum
?
How can you enumerate an enum
in C#?
例如以下代码无法编译:
E.g. the following code does not compile:
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
它给出了以下编译时错误:
And it gives the following compile-time error:
'Suit' 是一种'类型',但用作'变量'
'Suit' is a 'type' but is used like a 'variable'
它在 Suit
关键字上失败,第二个.
It fails on the Suit
keyword, the second one.
推荐答案
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}
注意:转换到 (Suit[])
并不是绝对必要的,但它确实使代码快了 0.5 ns.
Note: The cast to (Suit[])
is not strictly necessary, but it does make the code 0.5 ns faster.
这篇关于如何枚举一个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文