我有一个接口定义为:如何将列表<interface>转换为列表<concrete>?
public interface MyInterface {
object foo { get; set; };
}
和一个类实现该接口:
public class MyClass : MyInterface {
object foo { get; set; }
}
我然后创建返回ICollection的像这样的函数:
public ICollection<MyClass> Classes() {
List<MyClass> value;
List<MyInterface> list = new List<MyInterface>(
new MyInterface[] {
new MyClass {
ID = 1
},
new MyClass {
ID = 1
},
new MyClass {
ID = 1
}
});
value = new List<MyClass>((IEnumerable<MyClass>) list);
return value;
}
它会编译但会抛出一个
无法投射类型为 'System.Collections.Generic.List
1[MyInterface]' to type 'System.Collections.Generic.IEnumerable
1 [MyClass]'的对象。
异常。我究竟做错了什么?
这将工作在.Net 2.0+而不仅仅是LINQ,因为System.Collections.Generic.List <>直接支持ConvertAll()。 –
2011-05-16 15:44:12
谢谢,@Ritch。我认为'ConvertAll'是一个Linq方法,但我没有打扰到检查。 – 2011-05-16 15:47:35
这个伎俩!感谢JSBangs。 – acermate433s 2011-05-16 15:49:35