[英]NullReferenceException on trying to use my first user-defined type
What I'm trying to do is define my own type that contains 2 int
s to use in a 2-dimensional array. 我想做的是定义自己的类型,该类型包含2个
int
,用于二维数组。 The application for this is using the array indexes as x,y coordinates for objects in 2-d space to be displayed. 为此,应用程序将数组索引用作要显示的二维空间中对象的x,y坐标。 So object with data stored at
array[13,5]
would be displayed at x=13,y=5, and the properties of that object could be retrieved with array[13,5].property1
, for example. 因此,将数据存储在
array[13,5]
对象显示为x = 13,y = 5,并且可以使用array[13,5].property1
检索该对象的属性。 The type I've defined is extremely simple: 我定义的类型非常简单:
chunkBlocks.cs:
public class chunkBlocks {
public int blockType;
public int isLoaded;
}
then, I initialize the array: 然后,我初始化数组:
chunkBlocks[,] _bData = new chunkBlocks[17, 17];
This all compiles/runs without error. 所有这些都可以正确编译/运行。 The NRE is thrown when I try to assign a value to one of the properties of the type.
当我尝试为类型的属性之一分配值时,将引发NRE。 For debugging, I have the code written as:
为了进行调试,我将代码编写为:
_bData[i, n].blockType = 5;
and the NRE is thrown specifically on the .blockType
portion. NRE专门抛出在
.blockType
部分上。 I've tried changing the type to initialize with 0 values for both int
s to no avail: 我尝试将类型初始化为两个
int
都使用0值初始化,但无济于事:
public class chunkBlocks {
public int blockType = 0;
public int isLoaded = 0;
}
I've Googled around and searched SO, and I've not been able to turn up anything. 我已经在Google周围搜索并搜索了SO,但是我却无法打开任何东西。 I'm sure it's a relatively simple matter, but I'm not experienced enough to be able to pinpoint it.
我敢肯定这是一个相对简单的事情,但是我没有足够的经验来查明。
Thanks! 谢谢!
You need to initialize every instance of the array: 您需要初始化数组的每个实例:
_bData[i, n] = new chunkBlocks();
Now assign the value to it: 现在为其分配值:
_bData[i, n].blockType = 5;
You will have to initialize every instance, you just have declared them in the array. 您必须初始化每个实例,只需在数组中声明它们即可。
I think you should do this: 我认为您应该这样做:
for(int i = 0;i<17;i++)
{
for (int j = 0; j < 17; j++)
{
_bData[i, j] = new chunkBlocks ();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.