理解可能的空引用 return
understanding Possible null reference return
我开始在 VS19 预览版中收到这些警告,
<TargetFramework>net5.0</TargetFramework>
<LangVersion>preview</LangVersion>`
<Nullable>enable</Nullable>
这是一个来自 class 的示例,它将它的许多方法代理到 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
具有相同的签名?
解决此问题的最佳方法是什么?
例如Find method will return default(T) when no match, which is null when T is a reference type. If you want to prevent that, you could constrain your class只允许值类型。
中有描述
Returns
The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.
所以 return T?
或者可能使用 ??
来 return 一个非空值。
关于相同的签名,在代码中您可以看到:
[return: MaybeNull]
public T Find(Predicate<T> match)
Specifies that an output may be null even if the corresponding type disallows it.
我开始在 VS19 预览版中收到这些警告,
<TargetFramework>net5.0</TargetFramework>
<LangVersion>preview</LangVersion>`
<Nullable>enable</Nullable>
这是一个来自 class 的示例,它将它的许多方法代理到 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
具有相同的签名?
解决此问题的最佳方法是什么?
例如Find method will return default(T) when no match, which is null when T is a reference type. If you want to prevent that, you could constrain your class只允许值类型。
Returns
The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.
所以 return T?
或者可能使用 ??
来 return 一个非空值。
关于相同的签名,在代码中您可以看到:
[return: MaybeNull]
public T Find(Predicate<T> match)
Specifies that an output may be null even if the corresponding type disallows it.