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

标签 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);
        }
    }
}

最佳答案

因为泛型不是协/反变体:

Eric Lippert's blog对此有一篇很棒的帖子。

来自 Charlie Calvert is here 的另一篇文章.

关于c# - 为什么我不能将 IList<ChildType> 传递给 F(IEnumerable<ParentType>)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/632399/

相关文章:

c# - 如何允许与 Dynamics 服务器的一般连接

c# - 在 WCF 中使用创建自签名证书

c# - SQL Server 连接计数问题

c# - 如何检查所有两个对象的属性是否相等,包括派生属性?

c# - C#中目录的读取权限

c# - C#正则表达式仅匹配字符串中完整单词的一部分

c# - 什么是空的!声明是什么意思?

c# - 如何禁用所有按钮

c# - async/await - 我使用了错误的同步上下文吗?

c# - 从数据库表写入文本文件的最快方法是什么?