C#中Console.ReadLine()报“Converting null literal or possible null value to non-nullable type”错误求助
解决Console.ReadLine()空值转换错误的问题
这个错误是因为C# 8.0及以上版本默认启用了可空引用类型特性:Console.ReadLine()在用户未输入直接回车或流结束时会返回null,但你声明的testString是非可空的string类型,编译器检测到空值赋值风险,因此抛出该错误。
以下是几种可行的解决方法:
方法一:声明可空字符串变量
将变量类型改为string?,明确允许其接收null值:
using System; namespace Sample { class Test { public static void Main(string[] args) { string? testString; Console.Write("Enter a string - "); testString = Console.ReadLine(); Console.WriteLine("You entered '{0}'", testString); } } }
方法二:用空合并运算符提供默认值
如果需要确保变量始终非空,使用??运算符给null结果设置默认值(比如空字符串):
using System; namespace Sample { class Test { public static void Main(string[] args) { string testString; Console.Write("Enter a string - "); testString = Console.ReadLine() ?? ""; Console.WriteLine("You entered '{0}'", testString); } } }
方法三:临时禁用可空引用类型检查(不推荐)
若只是临时绕过检测,可在文件顶部添加#nullable disable指令关闭该特性,但长期使用会失去空引用异常的防护能力:
#nullable disable using System; namespace Sample { class Test { public static void Main(string[] args) { string testString; Console.Write("Enter a string - "); testString = Console.ReadLine(); Console.WriteLine("You entered '{0}'", testString); } } }
内容的提问来源于stack exchange,提问作者abd ert
相关产品推荐
相关产品推荐

