gpt4 book ai didi

c# - 为什么我不能将对象添加到我的 List<>?

转载 作者:太空宇宙 更新时间:2023-11-03 17:13:25 25 4
gpt4 key购买 nike

我有一个类 clsPerson,它看起来像这样:

public class clsPerson
{
public string FirstName;
public string LastName;
public string Gender;
public List<Book> 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", "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();
}
}

不过,我在 VS2013 中遇到错误,在 p.Books.Add(book1); 行上显示“NullReferenceException was unhandled”。

显然,我做错了什么。我想我可以创建几本书,然后将它们添加到我的 clsPerson 对象的名为 BooksList 中。当 book1 对象在我尝试将其添加到我的 Books 列表之前刚刚实例化时,我无法弄清楚为什么错误是“NullReferenceException”。有人可以给我指点或建议吗?

最佳答案

您没有在 Person 类中实例化 Books 集合

在你的 Person 构造函数中:

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

关于c# - 为什么我不能将对象添加到我的 List<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21394818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com