這不會奏效,因爲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
}
感謝您的快速反應。我將不得不做一些學習來了解你在告訴我什麼。 在更高層次上,我試圖完成的是:UI編碼器將我的集合視爲IList。 [我無法改變;它在我們的合同中。]但是,例如,當他編碼RemoveAt時,我需要他擊中FooList.RemoveAt,而不是List.RemoveAt。 – 2010-07-13 19:00:01
我添加了一個可能有助於說明一個潛在解決方案的示例。 – mquander 2010-07-13 19:56:14
這對我很有用。謝謝! – 2010-07-13 20:46:12