【问题标题】:Why IEnumerable not equivalent to list [duplicate]为什么 IEnumerable 不等于列表 [重复]
【发布时间】:2019-07-05 16:40:31
【问题描述】:

当我编写这段代码时,它允许我

IEnumerable<object> creator = new List<string>();

但是当我写的时候

IEnumerable<object> creator = new List<int>();

它显示编译时错误

错误 CS0266 无法隐式转换类型 'System.Collections.Generic.List' 到 'System.Collections.Generic.IEnumerable'。显式 存在转换(您是否缺少演员表?)

我不知道为什么会这样。

【问题讨论】:

标签: c#


【解决方案1】:

那是因为value types do not support co-/contravariance

string 是一个引用类型,所以它工作正常。 int 是值类型,所以不是。

但是,您可以将列表显式转换为带框的ints 列表:

IEnumerable<object> creator = listOfInts.Select(i => (object)i);

编辑:

与许多其他答案相反,值类型do in fact inherit from objectstruct usage guide 中也提到了这一点。这不是值类型不变的原因!

【讨论】:

    【解决方案2】:

    我相信这是因为 int 是一种值类型。虽然 int 最终确实继承自对象,但 int 不能继承自; 您可以将它们的基本类型与此进行比较:

    Console.WriteLine(10.GetType().BaseType.Name);
            Console.WriteLine("".GetType().BaseType.Name);
    

    【讨论】:

    • 是的,我确实指出了这一点。但是你不能从 int 继承。 “一个结构不能从另一个结构或类继承,也不能是一个类的基础。”
    猜你喜欢
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 2019-12-02
    • 2019-04-16
    相关资源
    最近更新 更多