使用Switch in for循环

时间:2013-08-12 23:01:14

标签: c# for-loop switch-statement

我已经收到过几次这个问题了,我想知道为什么我不能在交换机中使用我的索引,我收到一个错误,数组[index] = null,有什么原因吗?

// array of classes, im using public getters and setters to access the rank and cardcolor
Cardgame[] cardgame = new Cardgame[50];
int index = 0;
string CardColor = "";

...             

for (int i = 0; i < 4; i++)
{
    switch (i)
    {
        case 1: CardColor = "red";
            break;
        case 2: CardColor = "blue";
            break;
        case 3: CardColor = "diamond";
            break;
        case 4: CardColor = "candy!";
            break;
    }
    for (int x = 0; x <= 13; x++)
    {
        index++; 
     Cardgame[index].Color = CardColor;
        switch (x)
        {

            default: Cardgame[index].Number = x.ToString();
                break;
            case 11: Cardgame[index].Number = "Farmer";

                break;
            case 12: Cardgame[index].Number = "Queen";

                break;
            case 13: Cardgame[index].Number = "King";

                break;
        }
    }

3 个答案:

答案 0 :(得分:3)

因为你有一组Cardgame个对象。默认数组初始值设定项将所有对象设置为null。你必须先cardgame[index] = new Cardgame()

答案 1 :(得分:1)

// first define the possible values
var suits = new [] {"red", "blue", "diamond", "candy"};
var ranks = new [] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "farmer", "queen", "king"}

//var ranks = Enumerable.Range(1, 10).Select(n => n.ToString())
//                      .Concat(new [] {"farmer", "queen", "king"})
//                      .ToArray();

// given the known values, you just iterate over every possible index
for(int i = 0; i < suits.Length * ranks.Length; i++)
{
    Cardgame[i] = new CardGame();
    Cardgame[i].CardColor = suits[i % suits.Length];
    Cardgame[i].Number = ranks[i / ranks.Length];
}

// or some "harder" LINQ    
var Cardgame = (from s in suits
               from r in ranks
               select new CardGame(s, r)).ToArray();

答案 2 :(得分:0)

你正在迭代第一个循环5次,每次迭代14张牌......这是70张牌。

此外,您永远不会初始化任何卡片游戏对象。

你想做的事:

for (int i = 0; i < 4; i++)
{
    ...
    for (int x = 0; x < 13; x++)
    {
        Cardgame[index] = new Cardgame();            
        ...
        index++;
    }
    ...
}