问题
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