NullReferenceException和我不知道为什么

时间:2012-02-10 01:21:10

标签: c# .net list nullreferenceexception

我有两个班:

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

可能最终很简单。

3 个答案:

答案 0 :(得分:6)

Player构造函数中,只需初始化shots = new List<Shot>();

答案 1 :(得分:1)

您需要在Player构造函数中(或在添加它之前)新建镜头。

shots = new List<Shot>();

答案 2 :(得分:0)

我更喜欢下面的内容,只有在需要时才初始化镜头,如果你需要添加逻辑来访问镜头,你可以不必改变镜头的使用。

private List<Shot> _shots;

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