用下面的代码
abstract class Base
{
protected abstract T? GetValue<T>([CallerMemberName] string propertyName = "");
}
class Derived : Base
{
protected override T GetValue<T>([CallerMemberName] string propertyName = "")
{
return default;
}
}
编译器告诉我 return default;
我有一个 CS8603“可能返回空引用”,这是真的。但是,如果我附加 ?
到该方法的返回类型,以便读取(如抽象方法)protected override T? GetValue<T>([CallerMemberName] string propertyName = "")
编译器告诉我
- CS0508“Derived.GetValue(string)”:返回类型必须为“T”才能匹配覆盖的成员“Base.GetValue(string)”。
- CS0453 类型“T”必须是不可为 null 的值类型才能将其用作泛型类型或方法“Nullable”中的参数“T”。
我如何告诉编译器我的意图 GetValue<T>
可能会返回空引用,而不是该方法的返回类型应该是 Nullable<T>
?
最佳答案
解决方案是将 [return: MaybeNull]
属性放在方法覆盖上,如下所示:
[return: MaybeNull]
protected override T GetValue<T>([CallerMemberName] string propertyName = "")
{
return default;
}
编译器现在不再列出警告 CS8603。
关于c# - 修复方法覆盖中的 "CS8603: Possible null reference return",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70671069/