2011-09-22 41 views
0

我知道這不能編譯,但爲什麼不應該呢?返回列表中的具體實現

public interface IReportService { 
    IList<IReport> GetAvailableReports(); 
    IReport GetReport(int id); 
} 

public class ReportService : IReportService { 
IList<IReport> GetAvailableReports() { 
    return new List<ConcreteReport>(); // This doesnt work 
} 

IReport GetReport(int id){ 
    return new ConcreteReport(); // But this works 
} 
} 
+0

。 – jgauffin

回答

0

嘗試改變這種

IList<? extends IReport> GetAvailableReports() 
0

我最近自己遇到了這個問題,發現使用IEnumerable而不是List解決了這個問題。這是一個非常令人沮喪的問題,但是一旦我找到問題的根源,這是有道理的。

這裏的測試代碼我用來尋找解決方案:

using System.Collections.Generic; 

namespace InheritList.Test 
{ 
    public interface IItem 
    { 
     string theItem; 
    } 

    public interface IList 
    { 
     IEnumerable<IItem> theItems; // previously has as list... didn't work. 
            // when I changed to IEnumerable, it worked. 
     public IItem returnTheItem(); 
     public IEnumerable<IItem> returnTheItemsAsList(); 
    } 

    public class Item : IItem 
    { 
     string theItem; 
    } 

    public class List : IList 
    { 
     public IEnumerable<IItem> theItems; // List here didn't work - changed to IEnumerable 

     public List() 
     { 
      this.theItems = returnTheItemsAsList(); 
     } 
     public IItem returnTheItem() 
     { 
      return new Item(); 
     } 

     public IEnumerable<IItem> returnTheItemsAsList() 
     { 
      var newList = new List<Item>(); 
      return newList; 
     } 
    } 
} 
你可能要添加C#的標籤,以獲得更多的答案
相關問題