2013-04-24 63 views
5

我有一个类叫做播放卡,它从卡片类继承。我将它实例化为一个叫做chuckcards的对象。其中一个数据成员是CARD ID。我试图给这个值赋一个int。它是在类中声明的。 以下是它的实例化。给类对象一个值c#

playingcards[] chuckcards = new playingcards[10];

这里是我尝试分配值。

for (int ctr = 1; ctr < 10; ctr++) 
     { 

      chuckcards[ctr].cardID = ctr; 

      temp++; 
     } 

我得到的错误是不设置到对象的实例

对象引用。

我不知道我在做什么错?我可以创建一个将值分配给每个成员的方法吗?如果这样会对某些事情感到痛苦,但我可以做到这一点?或者他们是一个简单的方法?

回答

7

当你调用new playingcards[10],它仅创建其中有一个类型,它是null引用类型的默认占位符。您将有实际的新达playingcards来然后用它

for (int ctr = 1; ctr < 10; ctr++) 
    { 
     chuckcards[ctr] = new playcards{cardID=ctr}; 
     temp++; 
    } 

我所使用的对象初始化器到一行还简化代码。

这里是发生了什么:

var chuckcards = new playingcards[10]; 

结果如下:

chuckcards[0] = null 
... 
chuckcards[9] = null 

所以,你不能做

chuckcards[0].cardID 

,因为它实在是

null.cardID 

所以,一旦你初始化值会从此有一个参考的:

chuckcards[0] = new playingcards(); 
chuckcards[0].cardID = ctr; 

评估为

[ref to playingcards].cardID 

有效期

+0

谢谢。所以我创建了个人实例?那么我需要一次新的吗?或者说我去做'chuckcards [0] .cardName =“查克”;'我会再次提供吗?任何链接的语法帮助也将是伟大的:) – Yop 2013-04-24 13:21:08

+0

不,只在初始化。我在我的答案中加入了更好的解释 – 2013-04-24 13:21:33

+0

好的,希望目前的答案能够为你解释得很好 – 2013-04-24 13:25:57

4

你需要给chuckcards[ctr]一个对象实例:

chuckcards[ctr] = new playingcards(); 
chuckcards[ctr].cardID = ctr; 
5

您已经定义了10个槽阵列以保存播放卡的实例,但每个插槽仍为空
在进入循环之前,您需要在每个插槽中添加一个实例

chuckcards[0] = new playingcards(); 

等......(1,2,...9 =最高指数)

最终你可以在循环中检查是否已指定一个实例给特定插槽或不

for (int ctr = 0; ctr < 10; ctr++) 
{ 
    if(chuckcards[i] != null) 
    { 
     chuckcards[ctr].cardID = ctr; 
     temp++; 
    } 
} 

请记住,在零数组索引开始不是一个

+0

我意识到张贴后谢谢你:) – Yop 2013-04-24 13:22:45

3

chuckcards [点击率]为空,你必须初始化它

playingcards[] chuckcards = new playingcards[10]; 

for (int ctr = 0; ctr < 10; ctr++) 
{ 
    chuckcards[ctr] = new playingcards(); 
    chuckcards[ctr].cardID = ctr; 
} 
2

的chuckcards [点击率]为空。你需要实例化它。

for (int ctr = 1; ctr < 10; ctr++) 
{ 
    chuckcards[ctr] = new playingcards(); 
    chuckcards[ctr].cardID = ctr; 
    temp++; 
} 

要得到更少的代码,您可以创建另一个需要id的构造函数。那么你有:

for (int ctr = 1; ctr < 10; ctr++) 
{ 
    chuckcards[ctr] = new playingcards(ctr); 
    temp++; 
}