空值注释:不考虑数组索引检查

huangapple go评论72阅读模式
英文:

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] = &quot;A&quot;;

	for (int i = 0; i &lt; 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 &lt;LangVersion&gt;latest&lt;/LangVersion&gt;.

答案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.

https://github.com/dotnet/core/issues

huangapple
  • 本文由 发表于 2023年6月15日 15:12:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定