【问题标题】:Non-nullable default return null warning不可为空的默认返回空警告
【发布时间】: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


【解决方案1】:

TReturn : notnull 表示TReturn 必须是不可为空的类型(可以是值类型或不可为空的引用类型)。不幸的是,value of default for non-nullable reference types is still null,因此是编译器警告。

例如,如果您希望不可为空的引用类型的“默认”是使用无参数构造函数创建的任何内容,您可以这样做:

public TReturn TestMethod<TReturn>() where TReturn : notnull, new()
{
    return new TReturn(); 
}

【讨论】:

  • 为什么不直接使用 return new TReturn() 和 ‘new()` 约束?这保证了一个无参数的构造函数,并且在语法上更简单。
  • @JeremyCaney 我以为new() 只适用于引用类型 - 我错了......
猜你喜欢
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
相关资源
最近更新 更多