AccessViolationException while adding item to a list

五迷三道 提交于 2020-01-15 20:12:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!