【问题标题】:CS8625 Cannot convert null literal to non-nullable reference type warning for Interlocked.Exchange(ref c, null)CS8625 无法将 null 文字转换为 Interlocked.Exchange(ref c, null) 的不可为 null 的引用类型警告
【发布时间】:2020-11-18 07:55:23
【问题描述】:

以下代码在 .NET core 3.1 中正常工作,但错误生成警告CS8625 Cannot convert null literal to non-nullable reference type

#nullable enable
using System.Threading;

namespace InterlockedExchangeNullProblem {
  public class Class1 {
    public Class1() {
      object? o = new object();
      var o1 = Interlocked.Exchange(ref o, null); // ok
      class2? c = new class2();
      var c1 = Interlocked.Exchange(ref c, null); // error CS8625 Cannot convert null literal to non-nullable reference type.
    }
  }
  public class class2{}
}

如果它适用于object?,它也应该适用于class2?

【问题讨论】:

    标签: c# interlocked nullable-reference-types .net-5


    【解决方案1】:

    解决方案:

    var c2 = Interlocked.Exchange<class2?>(ref c, null);
    

    注意:编译器使 c1 的类型为 class2 而不是 class2?

    如果您同意这需要更正,请投票:

    developercommunity.visualstudio.com: Interlocked.Exchange: compiler choses wrong Exchange with nullable types

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多