You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:06:06