c# - 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;
}
}
}
}
解决方案
推荐阅读
- android - Firebase 查询函数只返回 false。(除布尔变量 doesExist 外,所有代码都有效)
- sql - 动态查询中返回错误结果的函数
- python - 错误信息:不知道 'doit(cf_key)' 是什么!(工厂,工厂文件)
- php - Gmail SMTP 凭据:无法发送邮件。邮件程序错误:SMTP 错误:无法验证
- flutter - 颤振:用流而不是setState()更新单独类中的值状态?
- python - 当字符串中存在非格式化大括号时,在 python 中格式化字符串的最佳方法
- .net-core - 仅在 .NET Core 3.1 项目中进行目标重建
- python - 我怎样才能使python可以在命令提示符下检查 SystemError
- .net - 如何使用 dotnet.exe 和 MSBuild.Sdk.Extras 定位 sl5?
- c - While循环中表达式周围的双括号