c# - 了解可能的空引用返回

标签 c# c#-8.0 nullable-reference-types c#-9.0

我开始在 VS19 预览版中收到这些警告

<TargetFramework>net5.0</TargetFramework>
<LangVersion>preview</LangVersion>`
<Nullable>enable</Nullable>

下面是一个类的示例,该类将其许多方法代理到 ImmutableList<T> :

class C<T> {
  readonly ImmutableList<T> composed;
  public C() => composed = ImmutableList<T>.Empty;
  ...
  public T Find(Predicate<T> match) => composed.Find(match);
  ...
}

warning CS8603: Possible null reference return. for the Find method

我不明白为什么,因为它与 ImmutableList<T>.Find 具有相同的签名? 解决这个问题的最佳方法是什么?

最佳答案

the docs 中对此进行了描述

Returns

The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.

因此返回 T? 或者使用 ?? 返回非空值。

关于相同的签名,在代码中您可以看到:

[return: MaybeNull]
public T Find(Predicate<T> match)

参见the code on github

还有docs for [MaybeNull]

Specifies that an output may be null even if the corresponding type disallows it.

关于c# - 了解可能的空引用返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63145379/

相关文章:

c# - 使用 StructureMap 在 Model-View-Presenter 模式中进行 Presenter 注入(inject)

c# - "Collection was of a fixed size"带有 POCO 的 EF4 异常

c# - 动态创建的路由仅在应用程序重新初始化时才有效

visual-studio - .NET Framework 项目中的可空引用类型不能与 IntelliSense 一起使用

c# - ms access数据库受密码保护时如何编写连接字符串?

c# 8 nullable + 字典<>

c# - 即使参数具有 notnull 约束,也会收到有关可空类型参数的错误

带有泛型参数的 C# 8.0 可为空引用类型功能

c# - 在 C# 8 中,为什么对新表达式的类型推断会导致可空引用?