c# - NullReferenceException 和我不知道为什么

标签 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

可能是一些最终简单的东西。

最佳答案

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

关于c# - NullReferenceException 和我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9221464/

相关文章:

c# - 从 ExecuteMethodCall() 获取枚举

c# - 使用 HttpPost 方法提交表单后 ASP.NET Core 重定向到同一页面

python - 根据列表中的以下元素获取第一个元素的范围

java - 无法理解如何在 java 中定义列表列表

c# - 无法将属性值设置为 sqldatareader 类型的目标类型

c# - ASP.NET:在某些情况下我应该担心内存泄漏吗? [C#]

c# - 上传Excel文件并提取数据-asp.net mvc 3

.net - Mono 中的尾调用消除

mysql - 如何从 .NET 上的 varchar 获取下一个相关 ID?

Python,切片列表?