C#是否可以为空,不能正确检测问题?

问题描述 投票:1回答:1

我正在迁移项目以支持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
1个回答
0
投票

[在将private readonly string? Value;用作字段时起作用(因此与?一起使用]

例如

public class TestClass
{
    private readonly string? Value;

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

public class TestClass
{
    private readonly string? Value;

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

© www.soinside.com 2019 - 2024. All rights reserved.