繁体   English   中英

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

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

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

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

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

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

// 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 提交报告,以便他们尽快解决此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM