2015-10-20 61 views
2

我在我的类中有一个泛型类型参数。为什么我可以这样做:通用左侧接口参数

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>(); 

如果双方实现都有一个共同的接口。

+3

将'BaseFoo'转换为接口并使用[Co-和Contravariance](https://msdn.microsoft.com/zh-cn/library/ee207183.aspx)。 –

+1

'桔子是一种水果,但你不能把一篮桔子当成一篮水果,因为你可以把一根香蕉加入篮子',但不知何故,我总是得到这个比喻错误。 – Maarten

回答

1

的事实,即

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 

查看更多here