【发布时间】:2019-11-18 02:43:15
【问题描述】:
在 c# 8 中使用子类约束时,如何指定泛型引用类型可以为空?我进行了一些搜索,但没有找到有用的结果。
我很清楚添加where T: class 来指定泛型类型参数T 是引用类型就足够了。这样,C# 8 的nullable 引用注释和警告功能就可以完美运行。
但是,在某些情况下,泛型类型参数T 是另一个类的子类型,例如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();
}
}
【问题讨论】:
-
我无法重新创建它。如果我启用可为空的引用类型,那么您的两个代码 sn-ps 都会编译。如果我禁用它,那么也不会。
-
我也无法重现。
-
尝试了构建,它奏效了。看来这是一个 VS/Resharper 智能感知问题。对不起。
-
很高兴你能成功
-
这是一个 C# 8 功能,可为 Nullable 引用类型。
标签: c# generics c#-8.0 nullable-reference-types