以下代码在 .NET Core 3.1 中运行正常,但会错误地生成警告 CS8625:不能将 null 文字转换为不可为空的引用类型:
#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?
。