在 C#8 中,我们现在可以启用可为空值,这意味着编译器默认将引用类型视为非空值,除非显式声明为可为空值。然而,当尝试返回带有 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
}
为什么编译器会标记这一行?
最佳答案
TReturn : notnull
表示 TReturn
必须是不可为 null 的类型(可以是值类型或不可为 null 的引用类型)。不幸的是,value of default
for non-nullable reference types is still null
,因此编译器发出警告。
例如,如果您希望不可空引用类型的“默认值”是使用无参数构造函数创建的任何内容,您可以这样做:
public TReturn TestMethod<TReturn>() where TReturn : notnull, new()
{
return new TReturn();
}
关于c# - 不可为空的默认返回空警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61920204/