Object reference not set to an instance of an object

前端 未结 4 1262
滥情空心
滥情空心 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

    Arrays are initialised to be empty - the Null reference is because HomeArray[i,j] is null, not because HomeArray[i,j].currentCell is null.

    UPDATE: If you have a statement where a couple of different things could be null, then I generally split that up into multiple lines to make it easier to tell what is null.

    For example, in your case:

    MessageBox.Show(HomeArray[i,j].currentCell.ToString());
    

    Either HomeArray[i,j] or HomeArray[i,j].currentCell could potentially be null and trigger a NullReferenceException - there is no way to tell which it was from the exception. If you split that statement up however:

    Cell cell = HomeArray[i,j].currentCell;
    MessageBox.Show(cell.ToString());
    

    In this case if HomeArray[i,j] is null then you get your NullReferenceException on the first, line whereas if cell is null you get it on the second line.

提交回复
热议问题