【发布时间】:2020-05-20 18:23:07
【问题描述】:
在 C#8 中,我们现在可以启用 nullables,这意味着默认情况下,编译器认为引用类型不为 null,除非明确声明为可为 null。然而,似乎编译器在尝试返回具有notnull 约束的默认泛型时仍会引发警告。考虑以下示例:
public TReturn TestMethod<TReturn>() where TReturn : notnull
{
return default; // default is flagged with a compiler warning for possible null reference return
}
我想如果我还强制返回类型必须有一个空的构造函数可能会有所帮助,但它会产生相同的结果:
public TReturn TestMethod<TReturn>() where TReturn : notnull, new()
{
return default; // default is flagged with a compiler warning for possible null reference return
}
为什么编译器会标记这一行?
【问题讨论】:
-
等待...
new()并不意味着“空构造函数” -
default对于引用类型仍然意味着null。 -
我很确定
default将始终返回null上课。即使有默认构造函数,它也不会尝试构造新实例。 -
@HotN:有了
new()约束,您可以改为调用return new TReturn()。 -
@JeremyCaney “无参数”的意思是“没有参数”。 “空”的意思是“没有身体”。我怀疑 OP 的意思是前者。
标签: c# non-nullable