不可为空的默认 return 空警告
Non-nullable default return null warning
在 C#8 中,我们现在可以启用可空值,这意味着默认情况下引用类型被编译器视为非空,除非显式声明为可空。然而,似乎编译器在尝试 return 具有 notnull
约束的默认泛型时仍会发出警告。考虑以下示例:
public TReturn TestMethod<TReturn>() where TReturn : notnull
{
return default; // default is flagged with a compiler warning for possible null reference return
}
我想如果我也强制 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
,因此编译器警告。
如果您希望非空引用类型的 "default" 是使用无参数构造函数创建的任何类型,例如,您可以这样做:
public TReturn TestMethod<TReturn>() where TReturn : notnull, new()
{
return new TReturn();
}
在 C#8 中,我们现在可以启用可空值,这意味着默认情况下引用类型被编译器视为非空,除非显式声明为可空。然而,似乎编译器在尝试 return 具有 notnull
约束的默认泛型时仍会发出警告。考虑以下示例:
public TReturn TestMethod<TReturn>() where TReturn : notnull
{
return default; // default is flagged with a compiler warning for possible null reference return
}
我想如果我也强制 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
,因此编译器警告。
如果您希望非空引用类型的 "default" 是使用无参数构造函数创建的任何类型,例如,您可以这样做:
public TReturn TestMethod<TReturn>() where TReturn : notnull, new()
{
return new TReturn();
}