c# - 修复方法覆盖中的 "CS8603: Possible null reference return"

标签 c# nullable-reference-types

用下面的代码

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/

相关文章:

c# - Global.asax 中的 ASP.NET 导入命名空间错误

c# - 无法加载文件或程序集 Microsoft.ReportViewer.WebForms.XmlSerializers

c# - 是什么 ?[]? C#中的语法?

c# - 绑定(bind)到值类型的通用类型参数 - 使它们可以为空

c# - Windows 应用程序的 Twitter OAuth Echo | PIN 码问题

c# - 如何在像一本大书这样的巨大字符串中找到一个字符串出现的次数

c# - 网格绑定(bind)列名称

c# - 为什么在使用非短路 AND 运算符时会取消引用可能为空的引用警告?

c# - 返回类型中引用类型的可空性与覆盖的成员不匹配