对象引用未设置为对象的实例 - C#

时间:2013-05-19 17:50:31

标签: c# runtime-error nullreferenceexception

我是c#的初学者,我不断收到'System.NullReferenceException'错误。我到处都看,但我似乎无法找到有用的解决方案。 我简化了下面的代码,以便更清楚。

namespace tile_test
{
    public class Game1 : Game
    {
        public static float bottomWorld = 38400f;
        public static float rightWorld = 134400f;
        public static int maxTilesX = (int)rightWorld / 16 + 1;
        public static int maxTilesY = (int)bottomWorld / 16 + 1;


        public Game1()
        {
            Tile[,] tile = new Tile[maxTilesX, maxTilesY];
            int x = 1;
            int y = 1;
            tile[x, y].active = false; //Error on this line.
        }
    }
}

Tile-class如下所示

namespace tile_test
{
    public class Tile
    {
        public bool active;
    }
}

有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:2)

您已声明一个数组来存储所需维度的Tile对象,但此数组的每个插槽都为NULL,您无法引用NULL尝试分配属性active

Tile[,] tile = new Tile[maxTilesX, maxTilesY];
int x = 1;
int y = 1;
tile[x, y] = new Tile() {active=false};

并且您需要为计划存储在数组中的每个Tile都使用这样的代码

答案 1 :(得分:2)

首先初始化tile[x, y]

tile[x, y] = new Tile();
tile[x, y].active = false;

要初始化数组的所有元素,您可以创建实用程序方法

 T[,] Create2DimArray<T>(int len1,int len2) where T: new()
    {
        T[,] arr = new T[len1, len2];
        for (int i = 0; i < len1; i++)
        {
            for (int j = 0; j < len2; j++)
            {
                arr[i, j] = new T();
            }
        }
        return arr;
    }

并将其用作

Tile[,] tile = Create2DimArray<Tile>(maxTilesX, maxTilesY);

答案 2 :(得分:0)

当您尝试执行不存在的对象(值为System.NullReferenceException)的操作时,抛出null - 在这种情况下,您的Tile位于1,1的位置数组尚不存在,因此数组将值null存储在适当的引用位置。

在尝试使用Tiles数组之前,需要实例化Tiles数组中的所有项目。当你创建数组时,它们都有默认的null值,因为堆上没有对象可供引用。

如果要一次创建所有切片,只需在创建数组后执行此操作:

for (int i = 0; i < maxTilesX; i++)
{ // loop through "rows" of tiles
    for (int j = 0; j < maxTilesY; j++)
    { // loop through corresponding "column" of tiles
        tile[i, j] = new Tile(); // create a Tile for the array to reference
        tile[i, j].active = false; // some initialization
    }
}

您知道,C#使用零索引数组,因此数组中的第一项实际上是tile[0, 0]:如果您想要阅读更多内容,请参阅MSDN C# Arrays Tutorial上的数组。对不起,如果你已经知道了!