为什么我不能在List 中添加对象?
我有一个类clsPerson,看起来像这样:
public class clsPerson { public string FirstName; public string LastName; public string Gender; public List Books; }
我有另一个类,Book,看起来像这样:
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; } }
我编写了一个程序来测试将对象序列化为XML。 到目前为止,这就是我所拥有的:
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", "JRR 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(); } }
我收到一个错误,在VS2013中,在行p.Books.Add(book1);
book1)上说“NullReferenceException未处理” p.Books.Add(book1);
。
显然,我做错了什么。 我以为我可以创建几本书,然后将它们添加到我的clsPerson
对象的名为Books
的List
。 当我试图将book1
对象添加到我的Books
列表之前刚刚实例化book1
对象时,我无法弄清楚为什么错误会出现’NullReferenceException’。 有人可以给我一个指针或一些建议吗?
您应该首先初始化您的列表:
if(p.Books == null) p.Books = new List();
在clsPerson
类构造函数中执行它更合适。
您没有在Person
类中实例化您的Books集合
在您的Person构造函数中:
public Person() { this.Books = new List(); }
在class
创建对象时,应该真正初始化对象。
试试这个:
public class clsPerson { public string FirstName; public string LastName; public string Gender; public List Books = new List (); }