[英]How to add 2D arrays to a list in C#?
I want to make a list of 2D (boolean) arrays. 我想列出2D(布尔)数组。 I have declared the empty list block itself and made an empty 2D boolean array called blockStructure .
我已经声明了空列表块本身,并制作了一个名为blockStructure的空2D布尔数组。 Also I made a method blocks where I give blockStructure a different value and then add it to the to the block list.
我还制作了一个方法块 ,在其中给blockStructure一个不同的值,然后将其添加到块列表中。
class TetrisBlock
{
public List<bool[,]> block;
public bool[,] blockStructure;
}
public Tetrisblock(Texture2D sprite)
{
blockTexture = sprite;
blockStructure = new bool[2, 2];
}
List<bool[,]> blocks()
{
blockStructure = new bool[,] // first 2D array
{
{ false, true},
{ false, false}
};
block.Add(blockStructure);
blockStructure = new bool[,] // second 2D array
{
{ true, true},
{ false, false}
};
block.Add(blockStructure);
return block;
}
public void draw (GameTime gameTime, SpriteBatch spriteBatch)
{
for (int x = 0; x < 2; x++)
{
for (int y = 0; y < 2; y++)
{
if (blok[1][x,y])
{
spriteBatch.Draw(sprite, new Vector2(blockTexture.Width*x, blockTexture.Height*y, Color.White)
}
}
}
}
The error that I get says that list block has value null. 我得到的错误是列表块的值为null。 For some reason the 2D arrays don't get added to the list.
由于某些原因,二维数组不会添加到列表中。 Does someone know a solution?
有人知道解决方案吗?
You must initialize the List<bool[,]> block
list before you can add items to it. 您必须先初始化
List<bool[,]> block
列表,然后才能向其中添加项目。 This line just defines the reference which at first refers to nothing, null
, but you must have a block = new List<bool[,]>()
for the list to be initialized 这行代码仅定义了引用,该引用最初不包含任何内容,为
null
,但是您必须具有一个block = new List<bool[,]>()
才能初始化列表
You never gave block
a value: 您从未给
block
赋值:
block = new List<bool[,]>();
Any reference type is null
by default until you instantiate it to something. 默认情况下,任何引用类型都为
null
,直到将其实例化为某种东西为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.