0

我需要从文本文件中读取,然后将每一行放入一个列表中,然后从该列表中读取。但我得到一个 NullReferenceException “对象引用未设置为对象的实例。” 在大约 7 行的同时异常。我已经尝试了我能想到的一切。提前致谢。

                StreamReader sre = new StreamReader(FILE_PATH);
                Books books = new Books();
                string line;
                while ((line = sre.ReadToEnd()) != null)
                {
                 //NullReferenceException is Right here
                 //I defined myLibraryBooks outside of this code; But it is in the same scope
                    myLibraryBooks.Add(new Books() { Author = books.Author.ToUpper(), Title = line.ToUpper(), ISBN = line, Publish_Date = line });
                }
                Console.Write("Enter Author's Name:");
                string input_to_find = Console.ReadLine();
                var author = from Authors in myLibraryBooks
                             where Authors.Author == input_to_find
                             select Authors;

                foreach (var book in author)
                {
                    Console.WriteLine(String.Format("      Author            Title            ISBN            Publish Date"));
                    Console.WriteLine(String.Format("       {0}          {1}              {2}                {3}", books.Author, books.Title, books.ISBN, books.Publish_Date));
                }
                sre.Dispose();
4

1 回答 1

1

您正在声明books,但它看起来并没有被设置为任何东西(除非您在构造函数中做了一些奇怪的事情)。基于此,我会说以下行可能会导致此异常:

      *Guessing Author is null...
books.Author.ToUpper()

利用 .NET 的调试工具,逐行检查代码以查看问题所在。

于 2013-02-25T16:50:17.107 回答