2012-02-10 112 views
3

我有兩個類:
的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

回答

6

在你Player構造,只是初始化shots = new List<Shot>();

1

您需要新的球員構造的鏡頭(或你添加到它之前)。

shots = new List<Shot>(); 
0

我喜歡下面的好一點,只有當你需要它初始化鏡頭,如果你需要添加邏輯來訪問擊球時,你可以在無需改變應用射擊的所有的地方。

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

相關問題