给类对象赋值c#
本文关键字:赋值 对象 | 更新日期: 2023-09-27 18:10:45
我有一个叫做playingcards的类,它继承自一个cards类。我将它实例化为一个名为chuckcards的对象。其中一个数据成员是CARD ID。我试着给这个值赋一个int。它在类中声明为public。下面是它的实例化方式。
playingcards[] chuckcards = new playingcards[10];
我是这样赋值的
for (int ctr = 1; ctr < 10; ctr++)
{
chuckcards[ctr].cardID = ctr;
temp++;
}
我得到的错误是
对象引用未设置为an对象的实例。
我不知道我做错了什么?我可以创建一个方法将值赋给每个成员吗?如果是这样的话,对某些事情来说会很痛苦,但我能做到吗?或者这是一种简单的方法?
当您调用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
您已经定义了一个包含10个插槽的数组来保存playingcards的实例,但是每个插槽仍然为空
在进入循环之前,需要用
chuckcards[0] = new playingcards();
等.....(1、2、……9 = max指数)
最终你可以在循环中检查你是否给一个实例分配了一个特定的槽
for (int ctr = 0; ctr < 10; ctr++)
{
if(chuckcards[i] != null)
{
chuckcards[ctr].cardID = ctr;
temp++;
}
}
记住,数组索引从0开始而不是1
您需要给chuckcards[ctr]
一个对象实例:
chuckcards[ctr] = new playingcards();
chuckcards[ctr].cardID = ctr;
chuckcards[ctr]为空,您必须实例化它
playingcards[] chuckcards = new playingcards[10];
for (int ctr = 0; ctr < 10; ctr++)
{
chuckcards[ctr] = new playingcards();
chuckcards[ctr].cardID = ctr;
}
chuckcards[ctr]为空。您需要实例化它。
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++;
}