Kev*_*vin 1 c# nullreferenceexception
我有一个类clsPerson,看起来像这样:
public class clsPerson
{
public string FirstName;
public string LastName;
public string Gender;
public List<Book> Books;
}
Run Code Online (Sandbox Code Playgroud)
我有另一个类,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;
}
}
Run Code Online (Sandbox Code Playgroud)
我编写了一个程序来测试将对象序列化为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", "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();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我在VS2013中收到一条错误,说"NullReferenceException未处理"在线p.Books.Add(book1);.
显然,我做错了什么.我以为我可以创造一个几本书,然后将它们添加到我的clsPerson对象的List叫Books.book1在我尝试将对象添加到Books列表之前刚刚实例化对象时,我无法弄清楚为什么错误会出现'NullReferenceException' .有人可以给我一个指针或一些建议吗?
您没有在Person班级中实例化您的Books集合
在您的Person构造函数中:
public Person()
{
this.Books = new List<Book>();
}
Run Code Online (Sandbox Code Playgroud)
您应该首先初始化您的列表:
if(p.Books == null)
p.Books = new List<Book>();
Run Code Online (Sandbox Code Playgroud)
在clsPerson类构造函数中执行它更合适.
| 归档时间: |
|
| 查看次数: |
5224 次 |
| 最近记录: |