Object reference not set to an instance of an object

前端 未结 4 1261
滥情空心
滥情空心 2021-01-18 19:45

I have a class Cell:

public class Cell
{
    public enum cellState
    {
        WATER,
        SCAN,
        SHIPUNIT,
        SHOT,
        HIT
    }

             


        
4条回答
  •  不思量自难忘°
    2021-01-18 20:08

    When you instantiate an array, the items in the array receive the default value for that type. Thus for

    T[] array = new T[length];
    

    it is the case that for every i with 0 <= i < length we have array[i] = default(T). Thus, for reference types array[i] will be null. This is why you are seeing the NullReferenceException. In your case Cell is a reference type so since you have

    HomeArray = new Cell [MAXCOL, MAXROW]; 
    

    and all you have done is establish an array of references to Cells but you never assigned those references to instances of Cell. That is, you told the compiler "give me an array that can hold references to Cells" but you did not tell the compiler "give me an array that can hold references to Cells and assign each of those references to a new instance of Cell." Thus, the compiler will set the initial value of those references to null. Therefore you need to initialize the HomeArray:

    for (int i = 0; i < MAXCOL; i++)  { 
        for (int j = 0; j < MAXROW; j++)  { 
            HomeArray[i, j] = new Cell();
        } 
    }
    

提交回复
热议问题