你能用特定类型的 class 子 class 泛型 class 吗?

Can you subclass a generics class with a specific typed class?

我有一个泛型 class 和一个提供特定类型的子class。

public abstract class GenericBase<T>
    where T:Interface1
{
}

我子class具有特定实现的泛型:

public class Customer:
    GenericBase<Type1>

(Type1 实现 Interface1).

我有另一个抽象基础 class 引用了这个:

protected GenericBase<Interface1> genericInstance;

最后,当我尝试将 genericInstance 分配给基础实例 class 时,它给了我一个编译器错误,说它 "cannot implicitly convert Customer to GenericBase<Interface1>".

base.genericInstance = new Customer(); //Compiler error

如果 CustomerGenericBase<Type1> 的子类型并且 Type1 实现了 Interface1,我不明白为什么会出现此错误。如果 CustomerGenericBase<Type1> 的子 class,它不是 GenericBase<Interface1> 的有效类型吗?

我想我对这里的泛型有一些误解;有没有办法允许这种行为?

C# 没有泛型 类 的协变性,这基本上意味着您不能将具有更多派生类型参数的值分配给具有较少派生类型参数的变量。

不过,只要满足一些条件,即如果参数类型仅用于协变位置,即作为 return 类型的方法和属性。

有关详细信息,请参阅 this 和其他文档。

在 C# 中,协变(将派生类型分配给基类型)不能应用于泛型 类。因此,您需要应用一个专门标记为协变的接口,在新的 IGenericBase 接口上使用 out parameter modifier

protected IGenericBase<Interface1> genericInstance = new Customer();

public interface IGenericBase<out T> {}

public abstract class GenericBase<T> : IGenericBase<T>
    where T:Interface1 {}

public interface Interface1 {}

public class Type1 : Interface1 {}

public class Customer: GenericBase<Type1> {}