类列表的空引用异常 [英] Null Reference Exception for Class Lists

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

问题描述

我是编程新手,在创建一个具有另一个类的列表属性的类然后在 main 中访问它时遇到了一个问题.在尝试将项目添加到列表后,我收到异常对象引用未设置为对象的实例"我在运行时收到此错误.我确实理解 List<> 引用为空,但我试图了解它为什么为空以及如何解决它.如果我只是在 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; }        
}

谢谢,我感谢所有的帮助!

Thank you, I appreciate all the help!

推荐答案

当您创建 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.

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

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