考虑以下几点:
var lines = new List<string>();
string path = "FileName.txt";
var reader = File.OpenText(path);
while (!reader.EndOfStream)
{
lines.Add(reader.ReadLine());
}
将Nullable
标志设置为enable
时,在csproj中,reader
是一个StreamReader?
,它给出了一个参数“item”的可能的空引用参数
编译器警告。即使我明确地将 reader
设置为 StreamReader
,问题仍然存在。
有没有办法在不关闭 Nullable
的情况下绕过这个警告?
最佳答案
我相信,问题描述中包含的警告并不完整。我重现了这个问题并得到了下一个编译器警告:CS8604 Possible null reference argument for parameter 'item' in 'void List<string>.Add(string item)
.下一行出现警告
lines.Add(reader.ReadLine());
因为List<string> lines
是不可为 null 的列表 string
值和方法 StreamReader.ReadLine()
可以返回 nullable string?
(参见 reference source)。因此,在上面的代码行中,这些是尝试添加 null
将字符串值放入不可为 null 的字符串列表中。
要解决此问题,您可以使用以下任一方法:
Use null-forgiving operator . 你肯定知道表达式
reader.ReadLine()
的结果不能是null
因为它是在未到达流末尾时执行的。因此,您可以使用 null-forgiving 运算符来抑制警告:lines.Add(reader.ReadLine()!);
检查表达式的结果是否为
reader.ReadLine()
为空。 如果您使用下一个代码,警告将消失:string? line = reader.ReadLine(); if (line != null) lines.Add(line);
更新
正如@IanRingrose 在评论中指出的条件 line != null
可以在循环中使用而不是条件 !reader.EndOfStream()
.使用这样的条件解可以更清晰:
string? line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
现在我们不需要在循环体中使用 null-forgiving 运算符或附加条件。
关于c# - 如何让 File.OpenText 返回不可为空的 StreamReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62988160/