问题描述:

I am reading from a list the co-ordinates of a piece of armour. When it finds that specific armour, its supposed to take that armour object, and add it to another list. Yet I receive a null object error (object reference not set to an instance of an object)?

foreach (Armour item in armousOnMap)

{

if (item.Row == _yPosition && item.Column == _xPosition)

{

armourInventory.Add((Armour)item);

}

}

网友答案:

Are all coordinates populated? i.e. not nulls?

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);
    }
}
网友答案:

You need to initialize list first, and the add items into it.

var armourInventory = new List<Armour>();

Add this line when you are making your list.

var armourInventory = new List<Armour>();
foreach (Armour item in armousOnMap)
{
    if (item.Row == _yPosition && item.Column == _xPosition)
    {                    
        armourInventory.Add((Armour)item);
    }
}
相关阅读:
Top