当返回具有可为空的约束的可为空的泛型时,C#8会发出警告 [英] C# 8 gives a warning when returning a nullable generic with nullable constraint

查看:152
本文介绍了当返回具有可为空的约束的可为空的泛型时,C#8会发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

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 可以可以为空,但也不能为空.允许同时使用stringstring?.我不相信有任何说法"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".

如果您想说:

  1. T可以为空
  2. T不可为空时,此类型仍可以返回null
  1. T is allowed to be nullable
  2. When T is non-nullable, then this type can still return null

然后您可以编写:

[return: MaybeNull]
public T Foo<T>()
    where T : class?
{
    return null!;
}

SharpLab

请注意,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屋!

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