[英]cannot inherit from base class
My code is as follows 我的代码如下
class BaseClass<T> where T : class
{
class DerivedClass<U, V>
where U : class
where V : U
{
BaseClass<V> _base;
}
}
error: The type 'V' must be reference type. 错误:类型'V'必须是引用类型。
Isn't 'V' here of type class ?? 这里不是'V'类型的类吗?
You can resolve this issue by adding a class
constraint to the V
type parameter: 您可以通过将
class
约束添加到V
类型参数来解决此问题:
class BaseClass<T> where T : class
{
class DerivedClass<U, V>
where U : class
where V : class, U
{
BaseClass<V> _base;
}
}
For an explanation, see from Eric Lippert's article (as commented above by Willem van Rumpt ). 有关解释,请参阅Eric Lippert的文章 (如以上Willem van Rumpt所评论)。
Isn't 'V' here of type class ??
这里不是'V'类型的类吗?
No it is not. 不它不是。
V
could be of System.ValueType
or any enum, or any ValueType
. V
可以是System.ValueType
或任何枚举,或任何ValueType
。
Your constraint just says that V
should be derived from U
where as U
is class. 您的约束条件只是说
V
应该从U
派生,因为U
是类。 It doesn't says that V
should be a class. 并不是说
V
应该是一类。
For example the following is perfectly valid, which contradicts with the constraint where T : class
. 例如,以下内容完全有效,这与
where T : class
的约束相矛盾。
DerivedClass<object, DateTimeKind> derived;
So you need to add where V : class
also. 因此,您还需要添加
where V : class
。
Eric Lippert has blogged the very same question . 埃里克·利珀特(Eric Lippert)在网志上也发表了同样的问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.