【问题标题】:Dereference of a possibly null reference inside Net6 IF statement在 Net6 IF 语句中取消引用可能为空的引用
【发布时间】:2021-12-03 16:33:44
【问题描述】:

在我的项目定义中使用带有 <Nullable>enable</Nullable> 的 NET 6:

if (!(await _context?.Applications.AnyAsync())) {

}

我得到提示“_context 可能在此处为空”,这就是我在其上使用 ? 的原因。

我收到警告:

Dereference of a possibly null reference.

我也试过了:

if (!(await _context?.Applications.AnyAsync()) ?? false) {

}

但这不会编译。我该如何解决这个问题?

【问题讨论】:

  • 我认为这是因为可能是不可等待的 null 案例。
  • 这里真正的问题是这样的上下文在这种情况下为空似乎并不明智。 它是可空的这是你的代码的真正问题,而不是如何处理可能的空值。
  • 在等待之前进行检查,并在上下文 IS 为空时处理需要发生的情况。即return 或抛出空参考。

标签: c# asp.net-core .net-6.0 c#-10.0


【解决方案1】:

试试这个:

if (_context != null && !(await _context.Applications.AnyAsync())) {

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-31
    • 2022-01-02
    • 1970-01-01
    • 2016-09-14
    • 2022-11-23
    • 2011-05-27
    • 2015-11-05
    • 1970-01-01
    相关资源
    最近更新 更多