不能从基础继承 class

cannot inherit from base class

我的代码如下

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

}

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

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

您可以通过向 V 类型参数添加 class 约束来解决此问题:

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

有关解释,请参阅 Eric Lippert's article (as commented above by Willem van Rumpt)。

Isn't 'V' here of type class ??

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

您的约束只是说 V 应该派生自 U,而 U 是 class。它并没有说 V 应该是 class。

例如,以下是完全有效的,这与约束 where T : class.

相矛盾
DerivedClass<object, DateTimeKind> derived;

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

Eric Lippert 已写博客 the very same question