【问题标题】:Why can't I add objects to my List<>?为什么我不能将对象添加到我的 List<>?
【发布时间】:2014-01-28 00:47:05
【问题描述】:

我有一个类 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 未处理”。

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

【问题讨论】:

  • 一般clsPerson是VB风格的命名约定;在 C# 中,您只需使用 Person 作为类名。更不用说您的命名约定在您的其他类中不一致。至少选择一种一致的命名类风格。最好是 C# 方式:)

标签: c# nullreferenceexception


【解决方案1】:

您没有在 Person 类中实例化您的 Books 收藏

在您的 Person 构造函数中:

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

【讨论】:

    【解决方案2】:

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

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

    在你的 clsPerson 类构造函数中这样做更合适。

    【讨论】:

    • 啊!非常感谢!计时器一到,我就会将此标记为答案。
    • 还要序列化你需要一个空的 book 构造函数
    【解决方案3】:

    class 中创建对象时,您应该真正初始化对象。

    试试这个:

    public class clsPerson
    {
        public string FirstName;
        public string LastName;
        public string Gender;
        public List<Book> Books = new List<Book>();
    }
    

    【讨论】:

    • 谢谢!我正是在上面 Selman22 的回答的帮助下做到了这一点。他的回答以三秒的优势击败了 Cam Bruce,但他们都建议我在 person 构造函数中初始化列表,我现在已经这样做了。不过再次感谢!
    • @KevinJ 在构造函数中这样做并不是最好的方法。想象一下,如果你有 2 或 3 个构造函数 :) 作为一般规则,在变量 deceleration 处初始化以降低NullReferenceExceptions 的风险
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    相关资源
    最近更新 更多