2010-07-13 128 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

相关问题