英文:
Nullability annotations: Array index check is not considered
问题
我刚刚发现了可空性注解未能正确识别数组索引检查的情况。
public void Test()
{
string?[] list = new string[10];
list[0] = "A";
for (int i = 0; i < list.Length; i++)
{
if (list[i] != null)
{
list[i].ToString(); // 错误:可能发生 NULL 解引用。
}
}
}
这只是分析器中的一个错误吗,还是它故意报告这个错误?我可以通过使用一个局部变量来避免这个错误,但这看起来仍然很奇怪。
我正在使用 .NET 6.0 和 <LangVersion>latest</LangVersion>
。
英文:
I just found that the nullability annotations fail to correctly recognize an array index check.
public void Test()
{
string?[] list = new string[10];
list[0] = "A";
for (int i = 0; i < list.Length; i++)
{
if (list[i] != null)
{
list[i].ToString(); // Error: Possible NULL dereferencing.
}
}
}
Is this just a bug in the analyzer, or is it intentionally reporting the error? I can avoid the error by using a local variable, but it still seems strange.
I'm using .NET 6.0 with <LangVersion>latest</LangVersion>
.
答案1
得分: 3
我猜,在技术上,另一个线程可能会更改底层引用。良好的防御性编程会像你所说的那样使用本地变量:
var item = list[i];
if (item is not null) {
item.ToString()
}
还要注意!=
可以被重写。我个人使用模式匹配形式的is null
/ is not null
。
如果你认为编译器中的空检查有问题,dotnet的Github问题跟踪可能是一个好的起点 — 至少他们可以告诉你确切的原因。
https://github.com/dotnet/core/issues
英文:
I guess technically, something could change the reference underneath from another thread. A good bit of defensive programming would be, as you say, using a local variable:
var item = list[i];
if (item is not null) {
item.ToString()
}
Also note that !=
can be overridden. I personally use the pattern matching form is null
/ is not null
.
If you think the null check in the compiler is wrong, the dotnet Github issues would be a good place to start -- they could at least tell you the exact reasoning.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论