为什么我不能将IList <ChildType>传递给F(IEnumerable <ParentType>)?

Mar*_*ham 1 c#

我想我可以传递一个IList<ChildClass>作为IEnumerable<ParentClass>,因为显然在ChildType列表中的每个对象也是ParentType的实例.但是我没有得到编译器的喜爱.我错过了什么?

编辑:添加功能Foo3,它做我想要的.谢谢!

namespace StackOverflow
{
    public class ParentClass
    {
    }

    public class ChildClass : ParentClass
    {
    }

    public class Test
    {
        // works
        static void Foo(ParentClass bar2)
        {
        }

        // fails
        static void Foo2(IEnumerable<ParentClass> bar)
        {
        }

        // EDIT: here's the right answer, obtained from the 
        // Charlie Calvert blog post 
        static void Foo3<T>(IEnumerable<T> bar) where T : ParentClass
        {
        }

        public static void Main()
        {
            var childClassList = new List<ChildClass>();

            // this works as expected
            foreach (var obj in childClassList)
                Foo(obj);

            // this won't compile
            // Argument '1': cannot convert from 
            // 'System.Collections.Generic.List<ChildClass>' 
            // to 'System.Collections.Generic.IEnumerable<ParentClass>' 
            Foo2(childClassList);

            // EDIT: this works and is what I wanted
            Foo3(childClassList);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*rke 5

因为泛型不是共同变体:

Eric Lippert的博客上有一篇很棒的帖子.

Charlie Calvert的另一篇文章就在这里.