C# 实现接口的泛型列表
我一直在阅读,能够理解为什么第一个例子有效,但第二个却不行。为什么第一段代码很好,但第二段代码无法编译 首先是好代码:C# 实现接口的泛型列表,c#,generics,C#,Generics,我一直在阅读,能够理解为什么第一个例子有效,但第二个却不行。为什么第一段代码很好,但第二段代码无法编译 首先是好代码: interface IFoo {} class Foo : IFoo { } class Bar : IFoo { } var list = new List<IFoo>(); list.Add(new Foo()); list.Add(new Bar()); 接口IFoo{} 类Foo:IFoo{} 类栏:IFo
interface IFoo {}
class Foo : IFoo { }
class Bar : IFoo { }
var list = new List<IFoo>();
list.Add(new Foo());
list.Add(new Bar());
接口IFoo{}
类Foo:IFoo{}
类栏:IFoo{}
var list=新列表();
添加(新的Foo());
添加(新条());
现在来看引入泛型的代码
interface IZar<TFoo> where TFoo : IFoo { }
class ZarFoo : IZar<Foo> { }
class ZarBar : IZar<Bar> { }
var list2 = new List<IZar<IFoo>>();
list2.Add(new ZarFoo());
list2.Add(new ZarBar());
接口IZar,其中TFoo:IFoo{}
类ZarFoo:IZar{}
类ZarBar:IZar{}
var list2=新列表();
列表2.Add(newzarfoo());
列表2.Add(new ZarBar());
这是无法编译的,因为ZarFoo无法转换为IZar,而它应该能够,因为它实现了IZar,其中Foo:IFoo?,因为IZar
不是。你不能就这样贬低界面
您必须使用out
,使IZar
co变量:
interface IZar<out TFoo> where TFoo : IFoo { }
因为IZar
不是。你不能就这样贬低界面
您必须使用out
,使IZar
co变量:
interface IZar<out TFoo> where TFoo : IFoo { }
非常好的例子,很好地说明了问题,感谢您花时间解释。MSDN链接在几个页面上都非常冗长!对于简短的版本-伟大的例子和说明问题非常好,感谢花时间解释。MSDN链接在几个页面上都非常冗长!短版-
interface IZar<out TFoo> where TFoo : IFoo
{
TFoo GetOne();
}
class ZarFoo : IZar<Foo>
{
public Foo GetOne()
{ return new Foo(); }
}
class ZarBar : IZar<Bar>
{
public Bar GetOne()
{ return new Bar(); }
}