加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – NullReferenceException,我不知道为什么

发布时间:2020-12-16 01:51:07 所属栏目:百科 来源:网络整理
导读:我有两节课: class Player{ public string Id { set; get; } public int yPos { set; get; } public ListShot shots; public Player(string _Id,int _yPos) { Id = _Id; yPos = _yPos; }}class Shot{ public int yPos { set; get; } public Shot(int _yPos)
我有两节课:

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>();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读