'T' 类型的表达式不能由类型“<null>”的模式处理

expression of type 'T' cannot be handled by a pattern of type '<null>'

这是一个最小的示例:

class C {
  public bool F<T>(T x) => x is null;
}

导致问题的真正代码在这里https://github.com/kofifus/With/blob/master/With.cs#L35

直到今天这个编译正常,但我刚刚升级到

Microsoft Visual Studio Community 2019 Preview Version 16.1.0 Preview 2.0

代码现在错误:

Error CS8511 An expression of type 'T' cannot be handled by a pattern of type '<null>'. Please use language version 'preview' or greater to match an open type with a constant pattern.

这是怎么回事?解决这个问题的正确方法是什么?

note1 - 我不想用 C# 语言预览 ATM
note2 - 如果我将 x is null 更改为 x==null

,它仍然可以编译

我非常怀疑你的断言总是有效的。

更新

如果它在之前的预览中确实有效,那可能是由于语言功能被丢弃了

可能您正在尝试与 null 进行比较,即 ==

public bool F<T>(T x) => x == null;

然而,检查泛型是否相等的更可靠的方法是使用 EqualityComparer<T>.Default。这尊重 IEquatable<T> 没有装箱以及 object.Equals,并处理所有 Nullable<T>nullable 类型

的提升细微差别
public bool F<T>(T x) => EqualityComparer<T>.Default.Equals(x, default(T));

Update

仅作记录,(as you can see here)

public bool F<T>(T x) => !(x is object);

基本上就是编译成

public bool F<T>(T x)
{
    return x == null;
}

相同
public bool F<T>(T x) => x == null;

添加到提到的解决方案中,事实上这曾经对你有用 is likely to be caused by a bug in the 2019 preview

However, in Visual Studio 2019 we improperly permitted this to compile in language versions 7.0, 7.1, 7.2, and 7.3. In Visual Studio 2019 Update 1 we will make it an error (as it was in Visual Studio 2017), and suggest updating to preview or 8.0.

似乎允许 is null 在开放泛型中 成为 C#8 的一部分,并且是 championed here. The error is likely to eventually tell you to upgrade to C#8(而不是 'preview')之后发布了。