我如何枚举枚举?

2023-09-02 01:16:44 作者:網名再好看妳也不會註意到

你怎么能枚举的枚举在C#?

例如,以下不会编译:

 公开枚举套装
{
    黑桃,
    心,
    俱乐部,
    钻石
}

公共无效EnumerateAllSuitsDemoMethod()
{
    的foreach(在西装套装西装)
    {
        DoSomething的(衣服);
    }
}
 

它给编译时错误:

  

西装'是一个'类型',但用类似变量

它未能对的套装的关键词,第二个之一。

解决方案

 的foreach(在Enum.GetValues​​西装套装(typeof运算(套装)))
{
}
 

怎样获取枚举型自定义的值

How can you enumerate an enum in C#?

E.g., the following does not compile:

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

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

It gives the compile time error:

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

It fails on the Suit keyword, the 2nd one.

解决方案

foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
}

相关推荐
 
精彩推荐
图片推荐