我正在编写一个控制台应用程序,有一些基本的功能,让用户有输入和反应基于用户的输入。在以前的(.net 3.1)中,我可以这样做:
string str=Console.ReadLine();
if(str==""){
Console.WriteLine("do this");
}
else {
Console.WriteLine("do that");
}由于这是一个新的操作系统,我只是尝试安装.net-6.0,而不考虑太多。但是,由于.net-6.0中的一些更新,Console.ReadLine()的返回类型现在是string吗?它是可空的,代码将变成如下:
string? str=Console.ReadLine();
if(str==""){
Console.WriteLine("do this");
}
else {
Console.WriteLine("do that");
}由于我希望从用户获得输入,所以我可以忽略这里使用与.net3.1相同的代码的警告,string? str=Console.ReadLine()是否为null并导致空引用异常。或者我可以在什么原因中从Console.ReadLine()生成null;
发布于 2021-12-08 08:27:11
根据Console.ReadLine的文档,只有当没有更多的输入时,该方法才返回null:
输入流中的下一行字符,如果没有更多行可用,则为null。
尽管如此,检查一下null还是很好的:
string? str=Console.ReadLine();
if (string.IsNullOrEmpty(str))
{
Console.WriteLine("do this");
}
else
{
Console.WriteLine("do that");
}或者,如果您完全确定不存在空值,只需使用! (null-forgiving) operator
https://stackoverflow.com/questions/70271865
复制相似问题