首页 > 解决方案 > C# nullable 未正确检测问题?

问题描述

我正在迁移一个项目以支持 C# 8.0 可空值,但我遇到了一种情况,看起来 Visual Studio 没有正确检测空值。如果您在 TestClass 构造函数中查看下面的代码,Console.WriteLine 方法将抛出 NullReferenceException,因为 this.Value 为 null 并且尚未分配。虽然 VS 没有警告或错误,但它认为这里一切都很好。我错过了什么吗,VS不应该对此发出警告吗?这里的值绝对是空的。谢谢!

#nullable enable

namespace TestNullable
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            TestClass test = new TestClass("MyString");
        }

        public class TestClass
        {
            private readonly string Value;

            public TestClass(string value)
            {
                System.Console.WriteLine(this.Value.Length.ToString());
                this.Value = value;
            }
        }
    }
}

标签: c#nullable

解决方案


推荐阅读