这不会奏效,因为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