CS8625 无法将 null 文字转换为 Interlocked.Exchange(ref c, null) 的不可空引用类型警告

Pet*_*ber 5 c# interlocked nullable-reference-types .net-5

以下代码在 .NET core 3.1 中可以正常工作,但会错误地生成警告CS8625 Cannot Convert null Literals 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{}
}
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*ber 4

解决方案:

var c2 = Interlocked.Exchange<class2?>(ref c, null);
Run Code Online (Sandbox Code Playgroud)

注意:编译器将 c1 改为class2类型class2?

如果您同意需要纠正此问题,请投票:

developercommunity.visualstudio.com:Interlocked.Exchange:编译器选择了可为 null 类型的错误 Exchange