C# 通用左侧接口参数
我的类中有一个泛型类型参数。为什么我可以这样做:C# 通用左侧接口参数,c#,C#,我的类中有一个泛型类型参数。为什么我可以这样做: BaseFoo<InterfaceImplementation> foo = new ChildFoo<InterfaceImplementation>(); 我希望能做这样的事情: BaseFoo<AnInterface> foo = new ChildFoo<InterfaceImplementation>(); BaseFoo<AnInterface> bar = new Chi
BaseFoo<InterfaceImplementation> foo = new ChildFoo<InterfaceImplementation>();
我希望能做这样的事情:
BaseFoo<AnInterface> foo = new ChildFoo<InterfaceImplementation>();
BaseFoo<AnInterface> bar = new ChildFoo<AnotherInterfaceImplementation>();
BaseFoo-foo=new-ChildFoo();
BaseFoo bar=新的ChildFoo();
两种实现都有一个公共接口 事实上
class A {}
class B : A {}
这并不意味着
class C<B> : C<A> {}
class C:C.将BaseFoo
转换为一个接口并使用。类似于“一个桔子是一个水果,但你不能把一篮桔子当作一篮水果,这样你就可以在篮子里放一根香蕉”,但不知怎的,我总是把这个比喻弄错了。
class C<B> : C<A> {}
IBaseFoo<out T> {} // this is covariant interface
IBaseFoo<in T> {} // this is contravariant interface