通用左侧接口参数

本文关键字:接口 参数 | 更新日期: 2023-09-27 18:18:40

在我的类中有一个泛型类型参数。为什么我可以这样做:

BaseFoo<InterfaceImplementation> foo = new ChildFoo<InterfaceImplementation>();

但不是这个?难道编译器不能判断出AnInterfaceInterfaceImplementation的实现吗?

BaseFoo<AnInterface> foo = new ChildFoo<InterfaceImplementation>();

我希望能够做这样的事情:

BaseFoo<AnInterface> foo = new ChildFoo<InterfaceImplementation>();
BaseFoo<AnInterface> bar = new ChildFoo<AnotherInterfaceImplementation>();

两个实现有一个公共接口。

通用左侧接口参数

事实上,

class A {}
class B : A {}

并不意味着

class C<B> : C<A> {}

你需要方差,但在c#中,它只适用于接口和委托。
您可以声明变量接口并从协变和逆变中进行选择:

IBaseFoo<out T> {} // this is covariant interface
IBaseFoo<in T> {} // this is contravariant interface