1
我一直在讀C# newbie List<Interface> question和可以理解爲什麼第一個例子中的作品,而不是第二。爲什麼第一個好,但第二個代碼沒有編譯。列表實現一個接口
首先是好碼:
interface IFoo {}
class Foo : IFoo { }
class Bar : IFoo { }
var list = new List<IFoo>();
list.Add(new Foo());
list.Add(new Bar());
現在對於它引入了泛型
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());
的代碼是不能編譯,因爲ZarFoo不能轉換爲IZAR時,想必應該能夠爲它實現了IZar Foo:IFoo?
很好的例子,並說明問題很好,謝謝花時間解釋。 MSDN鏈接在多個頁面上非常冗長!對於簡短版本 - https://msdn.microsoft.com/en-us/library/dd997386.aspx – user3791372