【问题标题】:Unhandled Exception: System.ArgumentNullException: Value cannot be null未处理的异常:System.ArgumentNullException:值不能为空
【发布时间】:2019-10-09 23:26:30
【问题描述】:

我正在尝试从 C# 中的文本文件中读取数据并将每一行分配给特定变量,但我得到了 Unhandled Exception: System.ArgumentNullException: Value cannot be null。尝试将字符串转换为 SongGenre 时出错。

public static void LoadSongs(string fileName)
{
    string title = "a";
    string artist;
    string length;
    string genre;
    TextReader reader = new StreamReader(fileName);
    while (title != null)
    {
        title = reader.ReadLine();
        artist = reader.ReadLine();
        length = reader.ReadLine();
        genre = reader.ReadLine();
        songs.Add(new Song(title, 
                           artist, 
                           Convert.ToDouble(length), 
                           (SongGenre)Enum.Parse(typeof(SongGenre), 
                           genre)));
    }
    reader.Close();
}

文件名指的是一个文本文件,可以。我尝试在这样的循环之外进行:

TextReader reader = new StreamReader(fileName);
string title = reader.ReadLine();
string artist = reader.ReadLine();
double length = Convert.ToDouble(reader.ReadLine());
SongGenre genre = (SongGenre)Enum.Parse(typeof(SongGenre), 
                                        reader.ReadLine());
songs.Add(new Song(title, artist, length, genre));

string title1 = reader.ReadLine();
string artist1 = reader.ReadLine();
double length1 = Convert.ToDouble(reader.ReadLine());
SongGenre genre1 = (SongGenre)Enum.Parse(typeof(SongGenre), 
                                         reader.ReadLine());
songs.Add(new Song(title1, artist1, length1, genre1));

它奏效了。 我还尝试使用 Console.WriteLine 打印流派,它正在工作,所以我确保它不为空,但我不知道为什么会收到此错误。

这不是其他问题的重复。循环无法正常工作,您可以在下面找到解决方法。

【问题讨论】:

  • 能否指出导致异常的指令?
  • 请发布一个完整的堆栈异常。我猜它发生在Enum.Parse。无论如何,如果没有minimal reproducible example,将很难提供帮助。您的代码可以优化,但对我来说看起来不错。错误可能是由于输入文件,ReadLine 可以返回null 如果“到达输入流的末尾”。
  • 您应该检查其中一个条目是否缺少文本文件中的“流派”。我认为这是 Enum.Parse 抛出 ArgumentNullException 的唯一原因。

标签: c# enums streamreader


【解决方案1】:

由于您设置循环的方式,您会遇到异常。你检查title 太早了。对于最后一次迭代,所有变量都将为空,并且在尝试解析空字符串时会出现异常。你需要这样的东西。

while (true)
{
    title = reader.ReadLine();
    if (title == null) break;
    artist = reader.ReadLine();
    length = reader.ReadLine();
    genre = reader.ReadLine();
    songs.Add(new Song(title, 
                       artist, 
                       Convert.ToDouble(length), 
                       (SongGenre)Enum.Parse(typeof(SongGenre), 
                       genre)));
}

这个例子并不完整,因为您可能应该处理输入文件的各种问题。 (例如,如果文件中没有足够的行,或者您正在解析的行不包含正确类型的数据怎么办)

要自己发现此类问题,您应该查看debugging。

【讨论】:

    猜你喜欢
    • 2020-03-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2020-09-25
    相关资源
    最近更新 更多