类列表的Null参考异常 [英] Null Reference Exception for Class Lists

查看:116
本文介绍了类列表的Null参考异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,在创建具有另一个类的list属性的类然后在main中访问它时遇到问题。尝试将项目添加到列表后,出现异常对象引用未设置为对象的实例,在运行时出现此错误。我确实了解List<>引用为null,但是试图理解为什么它为null以及如何解决它。如果仅在main中创建List,则我的代码将正常运行,但将来我希望将其作为一个类。就像我说的那样,我是OOP编程的新手,并试图获得一些有关为什么发生这种情况的信息。如果这是一个重复的问题,我深表歉意。我的代码段如下:

I am new to programming and am running into an issue when creating a class with a list property of another class and then accessing it in main. I am getting the exception "Object reference not set to an instance of an object" after trying to Add an item to the list I get this error during runtime. I do understand that the List<> reference is null but am trying to understand why it is null and how to get around it. My code will function properly if I just create the List in main but I would like to have it as a class in the future. Like I said I am new to programming OOP and trying to get some information regarding why this is happening. I apologize if this is a repeat question. My code snippet is below:

static void Main(string[] args)
    {
        BookList myBookList = new BookList();

        myBookList.bookList.Add(new Book("The Giver", "Lois Lowry", "Houghton Mifflin"));
        myBookList.bookList.Add(new Book("Telling Lies", "Paul Ekman", "Norton & Company"));
    }


class BookList
{
    public List<Book> bookList { get; set; }
}

class Book
{
    public Book(string title, string author, string publisher)
    {
        Title = title;
        Author = author;
        Publisher = publisher;
    }

    public string Title { get; set; }
    public string Author { get; set; }
    public string Publisher { get; set; }        
}

感谢您的帮助!

推荐答案

创建 BookList 时,实际上尚未初始化作为其成员的列表。您可以通过将初始化更改为以下方式来做到这一点:

When you create BookList, you haven't actually initialized the list that is its member. You can do this by changing your initialization to:

BookList myBookList = new BookList() {bookList = new List<Book>()};

或者通过编写 BookList 的构造函数初始化列表的类;

Or by writing a constructor for the BookList class which initializes the list; which would look like this:

class BookList
{
    public List<Book> bookList { get; set; }

    public BookList(){ //New constructor
        bookList = new List<Book>();
    }
}

出现此错误的原因是如果创建了BookList的实例,则实际上并没有确保 BookList 的内部 booklist 属性已初始化。就像您尝试执行此操作一样:

The reason you get this error is that while you've created an instance of BookList, you haven't actually make sure that the BookList's inner booklist property is initialized. It's like if you tried to do this:

List<string> newList;
newList.Add("foo");

那是行不通的,因为您只声明了 newList ,而不是初始化它。

That wouldn't work because you've only declared the newList, not initialized it.

这篇关于类列表的Null参考异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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