This question already has an answer here:
Assign Derived Class Collection to Base Class Collection compilation error
                                
                                    (1个答案)
                                
                        
                                6年前关闭。
            
                    
我有2节课:
ParentChild:Parent

当我下一步时:

IMyRepository<Child> _childRepository=new MyRepository<Child>();
IMyRepository<Parent> _repository=childRepository;


我收到错误“无法将源类型转换为目标类型”。
请告诉我为什么此代码不起作用。

最佳答案

因为,这样您就可以插入new AnotherDifferentChild() –在IList<Child>中不可能存在。如果您想了解更多详细信息,请查阅有关协方差,相反方差和不变性的文章。

如果要创建一个包含Parent类型引用的新列表,则可以使用LINQ中的Cast<T>()方法:

IList<Parent> parentList = childList.Cast<Parent>().ToList();

10-01 01:54
查看更多