将项目添加到列表时出现 AccessViolationException [英] AccessViolationException while adding item to a list

查看:27
本文介绍了将项目添加到列表时出现 AccessViolationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am developing a Windows Phone 8.0 App in VS2010

在某些时候,我决定创建 2 个类(玩家、游戏)

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

        }
}

当我调试时,应用程序在该行崩溃:Games.Add(HourGlass);由于 AccessViolationException,我看不出将项目添加到列表中有什么问题.

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 .

那是什么?

推荐答案

在使用列表之前,您必须对其进行初始化.

You must initialize a list before using it.

这个:

public List<Game> Games;

..必须是这样的:

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

我很惊讶您收到 AccessViolationException .. 我本以为会出现 NullReferenceException.

I am surprised you are getting an AccessViolationException.. I would have expected a NullReferenceException.

这篇关于将项目添加到列表时出现 AccessViolationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆