2010-07-13 88 views
0

(這是.net 3.5)我有一個實現IList的類FooList和一個實現IFoo的FooClass類。用戶需要IList<IFoo>。在我的實施中,我創建了一個名爲X的FooList<FooClass>。如何編碼我的退貨,以便我的FooList<FooClass> X成爲他的IList<IFoo>將自定義列表<CustomClass>投射到IList <Interface>

如果我嘗試

回報X.Cast().ToList();

他得到一個IList<IFoo>,但它不是我的FooList;它是一個List,並且是一個新的。

回答

1

這不會奏效,因爲FooList<FooClass>不是IList<IFoo>。這就是爲什麼:

var myList = new FooList<FooClass>(); 
IFoo obj = new SomeOtherFooClass(); 
IList<IFoo> result = (IList<IFoo>)myList; // hypothetical, wouldn't actually work 
result.Add(obj); // uh-oh, now myList has SomeOtherFooClass 

你需要或者進行復印或使用一個接口,在所包含的類型實際上協變,像IEnumerable<T>而不是IList<T>。或者,如果適用,您應該從開始處宣佈您的FooList<FooClass>FooList<IFoo>

這裏是一個小的實現,證明我的第二個建議:

public interface IFoo { } 
public class FooClass : IFoo { } 

public class FooList<T> : IList<T> 
{ 
    public void RemoveAt(int index) { /* ... */ } 
    /* further boring implementation of IList<T> goes here */ 
} 

public static void ListConsumer(IList<IFoo> foos) 
{ 
    foos.RemoveAt(0); // or whatever 
} 

public static IList<IFoo> ListProducer() 
{ 
    // FooList<FooClass> foos = new FooList<FooClass>(); // would not work 
    FooList<IFoo> foos = new FooList<IFoo>(); 

    foos.Add(new FooClass()); 

    return foos; // a FooList<IFoo> is an IList<IFoo> so this is cool 
} 

public static void Demo() 
{ 
    ListConsumer(ListProducer()); // no problemo 
} 
+0

感謝您的快速反應。我將不得不做一些學習來了解你在告訴我什麼。 在更高層次上,我試圖完成的是:UI編碼器將我的集合視爲IList。 [我無法改變;它在我們的合同中。]但是,例如,當他編碼RemoveAt時,我需要他擊中FooList.RemoveAt,而不是List.RemoveAt。 – 2010-07-13 19:00:01

+0

我添加了一個可能有助於說明一個潛在解決方案的示例。 – mquander 2010-07-13 19:56:14

+0

這對我很有用。謝謝! – 2010-07-13 20:46:12

相關問題