当返回具有可为空的约束的可为空的泛型时,C#8会发出警告 [英] C# 8 gives a warning when returning a nullable generic with nullable constraint
问题描述
此代码:
public T Foo<T>()
where T : class?
{
return null;
}
给出以下错误:
当"T"为非空值时,空值文字会引入空值 参考类型
A null literal introduces a null value when 'T' is a non-nullable reference type
当我们说T可以为空时,我不明白为什么我们不能返回空.如果我们另外尝试返回T?
,则会收到错误消息,指出T
必须不可为空.
I don't see why we can't return null when we say that T can be nullable. If we additionally try to return T?
we will get an error that T
has to be non-nullable.
似乎不可能具有可为空的约束并同时返回可为空的结果.
It seems it's kind of impossible to have a nullable constraint and return a nullable result at the same time.
推荐答案
想象您打电话:
string result = Foo<string>();
result
现在包含null
.但这是string
,不能为空.
result
now contains null
. But it's a string
, which is not nullable.
编译器警告您,在T
不可为空的情况下可能会调用Foo<T>
,在这种情况下返回null
会是意外的.
The compiler is warning you that Foo<T>
may be called where T
is not nullable, and returning null
in this case would be unexpected.
请注意,where T : class?
表示T
可以可以为空,但也不能为空.允许同时使用string
和string?
.我不相信有任何说法"T
必须为空".
Note that where T : class?
means that T
may be nullable, but it also might not be. Both string
and string?
are allowed. I don't believe there's any way to say "T
must be nullable".
如果您想说:
-
T
可以为空 -
T
不可为空时,此类型仍可以返回null
T
is allowed to be nullable- When
T
is non-nullable, then this type can still returnnull
然后您可以编写:
[return: MaybeNull]
public T Foo<T>()
where T : class?
{
return null!;
}
请注意,MaybeNull
仅适用于方法的合同,而不适用于其主体,这就是为什么我们需要返回null!
的原因.但是,您可以在上面的SharpLab链接中看到,调用方string result = Foo<string>();
收到了正确的警告.
Note that MaybeNull
only applies to the method's contract and not its body, when is why we need to return null!
. However you can see in the SharpLab link above that the caller string result = Foo<string>();
gets the correct warning.
这篇关于当返回具有可为空的约束的可为空的泛型时,C#8会发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!