Why can't I add objects to my List<>?

烈酒焚心 提交于 2020-01-14 04:17:34

问题


I have a class, clsPerson, that looks like this:

public class clsPerson
{
    public string FirstName;
    public string LastName;
    public string Gender;
    public List<Book> Books;
}

I have another class, Book, that looks like this:

public class Book
{
    public string Title;
    public string Author;
    public string Genre;        

    public Book(string title, string author, string genre)
    {            
        this.Title = title;
        this.Author = author;
        this.Genre = genre;
    }
}

I wrote a program to test serializing an object into XML. Here's what I have, so far:

class Program
{
    static void Main(string[] args)
    {
        var p = new clsPerson();
        p.FirstName = "Kevin";            
        p.LastName = "Jennings";
        p.Gender = "Male";

        var book1 = new Book("Neuromancer", "William Gibson", "Science Fiction");
        var book2 = new Book("The Hobbit", "J.R.R. Tolkien", "Fantasy");
        var book3 = new Book("Rendezvous with Rama", "Arthur C. Clarke", "Science Fiction");

        p.Books.Add(book1);
        p.Books.Add(book2);
        p.Books.Add(book3);

        var x = new XmlSerializer(p.GetType());

        x.Serialize(Console.Out, p);
        Console.WriteLine();
        Console.ReadKey();
    }
}

I'm getting an error, though, in VS2013 that says "NullReferenceException was unhandled" on line p.Books.Add(book1);.

Obviously, I'm doing something wrong. I thought that I could create a few books and then add them to my clsPerson object's List called Books. I can't figure out why the error is saying 'NullReferenceException' when the book1 object was just instantiated prior to me trying to add it to my Books list. Can someone offer me a pointer or some advice?


回答1:


You should initialize your list first:

if(p.Books == null)
   p.Books = new List<Book>();

It is more appropriate to do it in your clsPerson class constructor.




回答2:


You are not instantiating your Books collection in your Person class

In your Person constructor:

public Person()
{
  this.Books = new List<Book>();
}



回答3:


You should really initialize your objects when creating them in a class.

Try this:

public class clsPerson
{
    public string FirstName;
    public string LastName;
    public string Gender;
    public List<Book> Books = new List<Book>();
}


来源:https://stackoverflow.com/questions/21394818/why-cant-i-add-objects-to-my-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!