问题
I have a class:
public class ClientModelData
{
public int clientID { get; set; }
public IList<int> LocationIDs { get; set; }
}
When I call it:
ClientModelData obj = new ClientModelData();
obj.LocationIDs.Add(1);
It throws an exception:
`((System.Collections.Generic.ICollection<int>)(client.LocationID))' is null`
回答1:
LocationIDs
is not initialized therefore it is giving you the error.
public IList<int> LocationIDs { get; set; }
You should create an instance in the constructor
public ClientModelData()
{
LocationIDs = new List<int>();
}
回答2:
You should initialize your list with actual object, for example in the constructor. Add this to your class:
public ClientModelData()
{
LocationIDs = new List<int>();
}
来源:https://stackoverflow.com/questions/12684954/ilistint-throws-null-reference-exception-when-adding-values