当在 c# 8 中使用子类约束时,如何指定泛型引用类型可为空?

How do you specify that a generic reference type is nullable when a subclass constraint is used in c# 8?

当在 c# 8 中使用 subclass 约束时,如何指定泛型引用类型可为空?我进行了一些搜索,但没有找到有用的结果。

我很清楚,添加where T: class就可以指定泛型类型参数T是引用类型。这样,C# 8 的 nullable 引用注释和警告功能将完美运行。

但是,在某些情况下,泛型类型参数 T 是另一个 class 的子类型——比如 SomeClass。现在,当您添加 where T: SomeClass 时,您基本上是在告诉编译器 T 是引用类型,它是 SomeClass 的子类型,因为值类型不能是子类型属于参考类型。但是,对于C#8的nullable引用注解和警告特性,编译器似乎并不理解这一点。你如何让编译器清楚?

想看一些代码吗?这就是我的意思:

// this compiles
class ClassA<T> where T: class
{
    public GenericType<T?> DoSomething()
    {
        thrown new NotImplementedException();
    }
}
// this doesn't compile, but SomeClass is a class and it should work
class ClassA<T> where T: SomeClass
{
    // here, you get the classic:
    // Only non-nullable value type could be underlying of 'System.Nullable'
    // What this makes clear is that the compiler doesn't understand that
    // T is strictly a reference Type now
    public GenericType<T?> DoSomething()
    {
        thrown new NotImplementedException();
    }
}

您需要启用可空引用类型功能

一种方法是通过以下方式启用 #nullable

#nullable enable

我发布这个是为了让人们更容易找到它。就我而言,这实际上不是编译问题,只是 Resharper 的错误突出显示让我感到困惑。

要排除故障,只需尝试构建。如果没有错误并且您使用了 Resharper,那么 Resharper 就是罪魁祸首。您可以放心地忽略它。

我会向 Resharper 提交报告,以便他们尽快解决此问题。