我需要从文本文件中读取,然后将每行放入列表中,然后从该列表中读取。但我得到一个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();
答案 0 :(得分:1)
你声明books
,但它看起来并没有被设置为任何东西(除非你在构造函数中做了一些奇怪的事情)。基于此,我想说以下行可能会导致此异常:
*Guessing Author is null...
books.Author.ToUpper()
利用.NET的调试工具,逐行逐步查看代码,了解问题所在。