我可以将特定模型类的IList转换为MVC 3 .Net c#项目中类EntityObject的IList吗?特定的模型类(如果定义为EntityObject类的子类)。当我试着做演员时,我得到了一个错误:
无法转换'System.Collections.Generic.List
1[GesDis.Models.TiposCursosCEF]' to type 'System.Collections.Generic.IList1System.Data.Objects.DataClasses.EntityObject'.“类型的对象
发布于 2014-06-17 11:29:45
这是一个协方差的例子。也就是说,仅仅因为B是从A派生出来的,而且您可以分配A a = new B(),这并不意味着您可以将T<B>分配给T<A>。这些只是两种不同的泛型类型,而分配不起作用。
相反,您需要这样做:
IList<EntityObject> entityObjects = modelObjects.Cast<EntityObject>().ToList();发布于 2014-06-17 11:12:00
不,如果你能投的话,你可以做这样的事:
class Base {}
class Derived : Base {}
class SomeOther : Base {}
var list = new List<Derived>();
var baseList = (IList<Base>)list;
baseList.Add(new SomeOther()); // oops, add SomeOther to a List<Derived>https://stackoverflow.com/questions/24262011
复制相似问题