2012-09-22 38 views
0

我試圖返回IEnumerable<IMyInterface>。我有一個類,MyClass:IMyInterface,我從一個函數返回。返回IEnumerable <IMyInterface>將不起作用 - 必須使用IEnumerable <MyObj>而不是

IEnumerable<IMyInterface> test() { 
    tmpList = new List<MyClass>(); 
    tmp1 = new MyClass(); 
    tmp2 = new MyClass(); 
    tmpList.Add(tmp1); 
    tmpList.Add(tmp2); 
    return tmpList; 
} 

編譯器將不允許,這對我來說似乎很奇怪,因爲MyClass:MyInterface。編譯器給出的錯誤沿線'cannot implicitly convert type System.Collections.Generic.IEnumerable<MyClass> to System.Collections.Generic.IEnumerable<IMyInterface. An explicit conversion exists. Are you missing a cast?'

我不能執行返回(IEnumerable<IMyInterface>)tmp在運行時沒有強制異常。我錯過了什麼?我希望返回IEnumerable接口應該可以正常工作。

+1

MyClass的是'IMyInterface',這是不一樣的'的IEnumerable '。你想達到什麼目的? –

回答

5

你應該這樣做:

IEnumerable<IMyInterface> test() { 
    tmpList = new List<IMyInterface>(); // this is the important bit 
    tmp1 = new MyClass(); 
    tmp2 = new MyClass(); 
    tmpList.Add(tmp1); 
    tmpList.Add(tmp2); 
    return tmpList; 
} 

或者,你可以這樣做:

return tmpList.Cast<IMyInterface>(); // requires using System.Linq in usings 
+0

這是一個很好的建議。我故意給了一個微不足道的例子。在我的「真實」代碼中,我使用的工廠模式允許我生成列表,其中T必須是可新對象(不是接口)。所以我去了Cast - 精美的作品! – goldfinger

2

使用yield return而不是隻有return。這將一個簡單的對象變成對象的枚舉!

IEnumerable<IMyInterface> test() { 
    yield return new MyClass(); 
    yield return new MyClass(); 
    yield return new MyClass(); 
} 

創建實現接口的三個對象的枚舉。


編輯:

或改變方法的返回類型返回單個項目。

IMyInterface test() { 
    return new MyClass(); 
} 
+0

一個只包含一個對象。這是OP想要的嗎? –

+0

不知道他想要什麼。添加了一個沒有'IEnumerable <>'的例子。 –

+0

也許有用也指出,該函數實際上不會*運行*直到枚舉被訪問。有點屈服。 –

相關問題