为什么我不能将对象添加到我的 List<>? [英] Why can&#39;t I add objects to my List&lt;&gt;?

查看:50
本文介绍了为什么我不能将对象添加到我的 List<>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

我还有一个类 Book,看起来像这样:

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;
    }
}

我编写了一个程序来测试将对象序列化为 XML.到目前为止,这是我所拥有的:

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();
    }
}

不过,在 VS2013 中,我在 p.Books.Add(book1); 线上收到一个错误,提示NullReferenceException 未处理".

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

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

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?

推荐答案

你应该先初始化你的列表:

You should initialize your list first:

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

在您的 clsPerson 类构造函数中执行更合适.

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

这篇关于为什么我不能将对象添加到我的 List<>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆