0

我已经收到过几次这个问题,我想知道为什么我不能在 switch 中使用我的索引,我收到一个错误,即 array[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;
        }
    }
4

3 回答 3

3

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

于 2013-08-12T23:04:16.537 回答
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();
于 2013-08-12T23:21:26.117 回答
0

您在第一个循环中迭代 5 次,每次迭代 14 张卡片……那是 70 张卡片。

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

你想做:

for (int i = 0; i < 4; i++)
{
    ...
    for (int x = 0; x < 13; x++)
    {
        Cardgame[index] = new Cardgame();            
        ...
        index++;
    }
    ...
}
于 2013-08-12T23:04:31.973 回答