Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通用左侧接口参数_C# - Fatal编程技术网

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