的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 

可能最终很简单。

+0

pl.shots = new List (); pl.shots.Add(new Shot(pl.yPos)); – AJP 2012-02-10 01:25:18

在你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; 
    } 
} 
+0

这不是一个好的做法。你不应该在它自己内部初始化一个属性。它隐藏了潜在的路径,并且在与其他类一起使用时可能成为真正的问题。 – tsells 2012-02-10 01:45:54

+0

我想你可能需要'set'中的'新列表()'以及 – diaho 2012-02-10 01:47:08

+0

@tsells - 你能否进一步解释隐藏潜在路径? – 2012-02-10 01:54:19