C#:将可能返回null的Console.ReadLine赋值给非可空String的问题
解决C#中Console.ReadLine()返回null赋值给非可空string的编译问题
在C# 8及以后的版本中,可空引用类型特性会对「可能为null的值赋值给非可空变量」的行为抛出编译警告或错误,你遇到的就是这个问题——Console.ReadLine()返回的是string?(可空字符串类型),直接赋值给非可空的string变量会触发检查。以下是几种实用的处理方式:
强制忽略null警告(快速解决)
如果你能确定当前场景下输入不会是null(比如控制台环境中用户不会直接终止输入流),可以用null原谅运算符!告诉编译器跳过null检查:Console.Write("Please enter your name in the format of 'first last', for example: 'John Smith' or 'john smith' or 'john'."); string users_name = Console.ReadLine()!;注意:如果运行时真的出现null,后续使用该变量会抛出
NullReferenceException,仅适合你能确保输入非空的场景。主动检查并抛出异常(符合你的异常处理需求)
先将输入暂存到可空变量中,检查是否为null,若为null则主动抛出异常,确保后续使用的变量一定非空:Console.Write("Please enter your name in the format of 'first last', for example: 'John Smith' or 'john smith' or 'john'."); string? input = Console.ReadLine(); if (input is null) { throw new InvalidOperationException("输入不能为空,请重新运行程序。"); } string users_name = input;设置默认值(避免异常)
如果允许空输入的情况,可以用空合并运算符??给null输入设置一个默认值(比如空字符串):Console.Write("Please enter your name in the format of 'first last', for example: 'John Smith' or 'john smith' or 'john'."); string users_name = Console.ReadLine() ?? "";全局关闭可空检查(不推荐)
若想暂时关闭整个项目的可空引用类型检查,可以修改项目文件(.csproj)中的配置:<PropertyGroup> <Nullable>disable</Nullable> </PropertyGroup>不推荐这种方式,因为会失去C#可空类型带来的编译时安全防护,不利于代码健壮性。
内容的提问来源于stack exchange,提问作者Tyler Minix Glenn
相关产品推荐
相关产品推荐

