簡體   English   中英

NullReferenceException和我不知道為什么

[英]NullReferenceException and I Don't Know Why

我有兩節課:

class Player
{
    public string Id { set; get; }
    public int yPos { set; get; }
    public List<Shot> shots;
    public Player(string _Id, int _yPos)
    {
        Id = _Id;
        yPos = _yPos;
    }

}
class Shot
{
    public int yPos { set; get; }
    public Shot(int _yPos)
    {
        yPos = _yPos;
    }
}

當我嘗試將新鏡頭放入播放器的鏡頭列表中時,我得到NullReferenceException:

Player pl = new Player("Nick",50);
pl.shots.Add(new Shot(pl.yPos)); // this line throws exception

可能最終會變得簡單。

在你的Player構造函數中,只需初始化shots = new List<Shot>();

您需要在Player構造函數中(或在添加它之前)新建鏡頭。

shots = new List<Shot>();

我更喜歡下面的內容,只有在需要時才初始化鏡頭,如果你需要添加邏輯來訪問鏡頭,你可以不必改變鏡頭的使用。

private List<Shot> _shots;

public List<Shot> Shots
{
    get 
    { 
        if (_shots == null) 
        {
            _shots = new List<Shot>();
        }
        return _shots;
    }
    set
    {
        _shots = value;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM