的NullReferenceException,我不知道为什么
问题描述:
我有两个类:
的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>();
答
您需要新的球员构造的镜头(或你添加到它之前)。
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;
}
}
pl.shots = new List(); pl.shots.Add(new Shot(pl.yPos)); –
AJP
2012-02-10 01:25:18