2015-02-23 139 views
0

我的代码如下不能从基类继承

class BaseClass<T> where T : class 
{ 
    class DerivedClass<U, V> 
     where U : class 
     where V : U 
    { 
     BaseClass<V> _base; 
    } 

} 

错误:类型“V”必须是引用类型。

这里不是'V'类型的类?

+0

实施起来确实不够智能,而且成本太高。 Eric Lippert解释说:http://ericlippert.com/2013/07/15/why-are-generic-constraints-not-inherited/ – 2015-02-23 10:22:17

回答

6

您可以通过添加一个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评论)。

3

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