不能从基类继承
问题描述:
我的代码如下不能从基类继承
class BaseClass<T> where T : class
{
class DerivedClass<U, V>
where U : class
where V : U
{
BaseClass<V> _base;
}
}
错误:类型“V”必须是引用类型。
这里不是'V'类型的类?
答
您可以通过添加一个class
约束到V
类型参数解决这个问题:
class BaseClass<T> where T : class
{
class DerivedClass<U, V>
where U : class
where V : class, U
{
BaseClass<V> _base;
}
}
有关说明,从Eric Lippert's article看到(如上由Willem van Rumpt评论)。
答
Isn't 'V' here of type class ??
不,它不是。 V
可能是System.ValueType
或任何枚举或任何ValueType
。
您的约束条件只是说V
应来自U
,其中U
是类。它并不是说V
应该是一个类。
例如,以下内容是完全有效的,这与约束where T : class
相矛盾。
DerivedClass<object, DateTimeKind> derived;
因此,您还需要添加where V : class
也。
Eric Lippert的博客the very same question。
实施起来确实不够智能,而且成本太高。 Eric Lippert解释说:http://ericlippert.com/2013/07/15/why-are-generic-constraints-not-inherited/ – 2015-02-23 10:22:17