问题
I am developing a Windows Phone 8.0 App in VS2010
and in some point , i decided to make 2 classes (Player,Game)
Game.cs
public class Game
{
public string Name { get; set; }
public bool[] LevelsUnlocked { get; set; }
public bool firstTimePlaying { get; set; }
public Game(int numOfLevels)
{
this.firstTimePlaying = true;
this.LevelsUnlocked = new bool[numOfLevels];
}
}
Player.cs
public class Player
{
public int ID { get; set; }
public string FirstName{ get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public int Rank { get; set; }
public int Points { get; set; }
public string RankDescreption { get; set; }
public Uri Avatar { get; set; }
public List<Game> Games;
public Player()
{
Game HourGlass = new Game(6);
Game CommonNumbers = new Game(11);
Games.Add(HourGlass);
Games.Add(CommonNumbers);
}
}
When i debug , the app crashes at the Line : Games.Add(HourGlass);
because of AccessViolationException
, i don't see what is the problem of adding the item to the list .
so what is it ?
回答1:
You must initialize a list before using it.
This:
public List<Game> Games;
..needs to be this:
public List<Game> Games = new List<Game>();
I am surprised you are getting an AccessViolationException
.. I would have expected a NullReferenceException
.
回答2:
You haven't set your Games to a new list.
public List<Game> Games = new List<Game>();
public Player()
{
Game HourGlass = new Game(6);
Game CommonNumbers = new Game(11);
Games.Add(HourGlass);
Games.Add(CommonNumbers);
}
来源:https://stackoverflow.com/questions/23697956/accessviolationexception-while-adding-item-to-a-list