为什么 IList<childT> 无法转换为 IList<parentT>?

Fra*_*k59 2 c# inheritance

我有 2 个课程:\nParentChild:Parent.

\n\n

当我下一步时:

\n\n
IMyRepository<Child> _childRepository=new MyRepository<Child>();\nIMyRepository<Parent> _repository=childRepository;\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n

kni*_*ttl 5

因为,那么您将能够插入new AnotherDifferentChild()\xe2\x80\x93 ,这不可能存在于IList<Child>. 如果您想了解更多详细信息,请查找有关协方差逆变不变性的文章。

\n\n

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

\n\n
IList<Parent> parentList = childList.Cast<Parent>().ToList();\n
Run Code Online (Sandbox Code Playgroud)\n