不能从基类继承

时间:2015-02-23 10:16:07

标签: c# inheritance

我的代码如下

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

}

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

类型类不是'V'吗?

2 个答案:

答案 0 :(得分: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所述)。

答案 1 :(得分:3)

  

类型类不是'V'吗?

不,不是。 V可以是System.ValueType或任何枚举,也可以是ValueType

您的约束只是说V应该来自U,其中U是等级。它并没有说V应该是一个类。

例如,以下内容完全有效,这与约束where T : class相矛盾。

DerivedClass<object, DateTimeKind> derived;

因此您还需要添加where V : class

Eric Lippert在博客上发表了the very same question