Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

c# - 如何枚举枚举?(How to enumerate an enum?)

How can you enumerate an enum in C#?

(您如何enum C#中的enum ?)

Eg the following code does not compile:

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

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

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

And gives the following compile-time error:

(并给出以下编译时错误:)

'Suit' is a 'type' but is used like a 'variable'

(“西装”是“类型”,但像“变量”一样使用)

It fails on the Suit keyword, the second one.

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

  ask by Ian Boyd translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit)))
{
}

Note : The cast to (Suit[]) is not strictly necessary, but does make the code 0.5 ns faster.

(注意 :强制转换为(Suit[])并不是绝对必要的, 但是可以使代码快0.5 ns。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...