将 Console.ReadLine() 的空文字转换为字符串输入

She*_*eel 9 .net c# console-application

我是 C# 新手,所以我需要一些指导。

string NumInput = Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

在我的代码中,这个语句给出了警告

将 null 文字或可能的 null 值转换为不可为 null 的类型。

是否有任何替代此代码行或任何可以使此警告消失的内容

Sea*_*rty 13

首先,您看到此消息是因为您在项目中启用了 C# 8 Nullable 引用类型功能。Console.ReadLine()返回一个可以是字符串null 的值,但您使用它来设置string类型的变量。相反,可以使用var关键字将变量隐式设置为与返回值相同的类型,也可以手动将变量设置为nullable string string?类型。表示?可为空的引用类型。

然后,您可能需要在使用变量之前检查变量是否确实包含字符串:

string? NumInput = Console.ReadLine();
if (NumInput == null)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)