Null Reference Exception for Class Lists

后端 未结 3 1299
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 05:16

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 \"

3条回答
  •  一向
    一向 (楼主)
    2020-12-12 05:31

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

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

    class BookList
    {
        public List bookList { get; set; }
    
        public BookList(){ //New constructor
            bookList = new List();
        }
    }
    

    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 newList;
    newList.Add("foo");
    

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

提交回复
热议问题