将项添加到列表时AccessViolationException

时间:2014-05-16 14:34:13

标签: c# windows-phone-8

我正在VS2010中开发Windows Phone 8.0应用程序

并且在某些时候,我决定制作2个班级(玩家,游戏)

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);

        }
}

当我调试时,应用程序在Line处崩溃:Games.Add(HourGlass); 因为AccessViolationException,我没有看到将项目添加到列表中的问题。

那是什么?

2 个答案:

答案 0 :(得分:2)

您必须在使用之前初始化列表。

此:

public List<Game> Games;

..需要这样:

public List<Game> Games = new List<Game>();

我很惊讶你得到的是AccessViolationException ..我本来期望NullReferenceException

答案 1 :(得分:1)

您尚未将游戏设置为新列表。

 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);

        }