2013-02-22 23 views
-4

我從列表中讀取了一件盔甲的座標。當它發現特定的裝甲時,它應該攜帶該裝甲對象,並將其添加到另一個列表中。然而,我收到一個空對象錯誤(對象引用未設置爲對象的實例)?當我想從列表中添加時,爲什麼會收到空錯誤異常?

foreach (Armour item in armousOnMap) 
     { 
      if (item.Row == _yPosition && item.Column == _xPosition) 
      {      
       armourInventory.Add((Armour)item); 
      } 
     } 
+3

你確定'armourInventory'被初始化爲'new List '? – MarcinJuraszek 2013-02-22 07:10:03

+0

armourInventory是什麼,它是如何實例化的? – 2013-02-22 07:10:23

+1

哪條線路故障?基本上,* something *爲null - 無論是'item'還是'armousOnMap'或'armourInventory'。除此之外,我們不能用這麼少的信息來幫助你。請參閱http://tinyurl.com/so-list – 2013-02-22 07:11:27

回答

0

所有座標是否填充?即不是空值?

var armourInventory = new List<Armour>(); 

foreach (Armour item in armousOnMap) 
{ 
    if ((item.Row != null && item.Row == _yPosition) && (item.Column != null && item.Column == _xPosition)) 
    {      
     armourInventory.Add((Armour)item); 
    } 
} 
0

您需要首先初始化列表,然後在其中添加項目。

var armourInventory = new List<Armour>(); 

當您製作清單時添加此行。

var armourInventory = new List<Armour>(); 
foreach (Armour item in armousOnMap) 
{ 
    if (item.Row == _yPosition && item.Column == _xPosition) 
    {      
     armourInventory.Add((Armour)item); 
    } 
} 
相關問題