gpt4 book ai didi

c# - 未从FirstOrDefault公开的可为空的引用类型信息

转载 作者:行者123 更新时间:2023-12-05 00:10:04 27 4
gpt4 key购买 nike

我想测试C#8.0中的新nullable reference types功能。

我启动了一个针对.NET Core 3.0的新项目,在.csproj文件中启用了可为空的引用类型,并开始进行编码。我创建了一个简单列表,该列表接受string[]并在等于string的数组中返回abc。现在,由于不确定该数组中是否确实存在abc,因此我使用FirstOrDefault(),如果未找到匹配项,则默认为null

using System;
using System.Linq;

public string FindArgument(string[] args)
{
var arg = args.FirstOrDefault(x => x == "abc");
return arg;
}

我的方法返回 string,它现在应该是不可为null的类型。由于 FirstOrDefault()可能返回 null,因此我希望上述方法在返回可能为空的 arg变量时产生警告。它不是。

查看Visual Studio中 FirstOrDefault()的签名 ,可以清楚地知道的原因:该方法返回的是 string,而不是我期望的可为空的等效 string?

使用下面的方法主体确实会产生我期望的警告:

var arg = args.Contains("abc") ? "abc" : null;
return arg;

在面向.NET Core 3.0时,系统库(在本示例中为 System.Linq)是否真的不公开可空性信息?

最佳答案

看起来System.Linq在3.0版本中不是不可为空的。因此,可为空的引用类型不会发出正确的警告。

您可以在roslyn repo中检查类似的问题。 This open issue on Github与您的问题非常相似。在该期中,贡献者解释了当前的问题:

System.Linq is nullable annotated in master branch of corefx, but not in release/3.0. So there's nothing unexpected in compiler. The compiler should provide some diagnostics showing that you are using nullable-oblivious stuff.

关于c# - 未从FirstOrDefault公开的可为空的引用类型信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58670909/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com