未从FirstOrDefault公开的可为空的引用类型信息 [英] Nullable reference type information not exposed from FirstOrDefault

查看:96
本文介绍了未从FirstOrDefault公开的可为空的引用类型信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试新的可引用类型 C#8.0中的功能.

I wanted to test out the new nullable reference types feature in C# 8.0.

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

I started a new project targeting .NET Core 3.0, enabled nullable reference types in the .csproj file, and started coding. I created a simple list that takes a string[] and returns the string in that array that equals abc. Now, because I am not certain that abc actually exists in the array, I use FirstOrDefault(), which should default to null if a match is not found.

using System;
using System.Linq;

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

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

My method returns string, which should now be the non-nullable type. Since FirstOrDefault() may return null, I would expect the above method to yield a warning when returning the maybe null arg variable. It does not.

在Visual Studio中,查看FirstOrDefault()的签名,很清楚:该方法返回string,而不是我期望的可为空的等效string?.

Looking at the the signature for FirstOrDefault() in Visual Studio, it is clear why: The method returns a string, not the nullable equivalent string? I would expect.

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

Using the method body below does yield the warning I expected:

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

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

Do system libraries (in this example System.Linq) really not expose nullability information when targeting .NET Core 3.0?

推荐答案

在3.0版本中,类似System.Linq的注释不能为空.因此,可为空的引用类型不会发出正确的警告.

Looks like System.Linq is not nullable annotated in the 3.0 release. So Nullable Reference Types does not emit the correct warning.

您可以在在Github上公开的问题与您的问题非常相似.在该期中,贡献者解释了当前的问题:

You can check similar problems in the roslyn repo. This open issue on Github is very similar to your problem. In that issue a contributor explains the current problem:

System.Linq在corefx的 master 分支中带注释,但在 release/3.0 中没有.因此,编译器中没有任何意外. 编译器应提供一些诊断信息,表明您正在使用可为空的东西.

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.

这篇关于未从FirstOrDefault公开的可为空的引用类型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆