【问题标题】:Why can't I return a variable of type List<List<int>> for a function that has a IList<IList<int>> return type in C# [duplicate]为什么我不能为 C# 中具有 IList<IList<int>> 返回类型的函数返回 List<List<int>> 类型的变量 [重复]
【发布时间】:2015-08-21 02:30:58
【问题描述】:
public IList<IList<int>> FunctionName(...)
{
    var list = new List<List<int>>();
    ...
    //return list;                      // This doesn't compile (error listed below)
    return (IList<IList<int>>)list;     // Explicit cast compiles
}

当我直接返回“list”时,我得到这个错误:

> "Cannot implicitly convert type
> 'System.Collections.Generic.List<System.Collections.Generic.List<int>>'
> to
> 'System.Collections.Generic.IList<System.Collections.Generic.IList<int>>'.
> An explicit conversion exists (are you missing a cast?)"

接口返回类型不应该接受任何派生实例吗?

【问题讨论】:

  • 它对我有用:/。你能告诉我们更多关于框架和语言版本的细节吗?
  • “接口返回类型不应该接受任何派生实例吗?” – 是的,但是List&lt;List&lt;int&gt;&gt; 的接口类型是IList&lt;List&lt;int&gt;&gt;。因为List&lt;T&gt; 实现了IList&lt;T&gt;。它没有说明内部不同Ts 的类型转换。由covariance and contravariance 处理。
  • @Misters:您使用的是什么语言版本?我从未见过允许这样做的 c# 编译器。
  • 尝试同时针对 .NET 4.5 和 .NET 4.0,同样的错误:/

标签: c# interface covariance


【解决方案1】:

有一个微妙的类型错误。如果这行得通,您就有可能出现这类错误。

List<List<int>> list = new List<List<int>>();
IList<IList<int>> ilist = list;  // imagine a world where this was legal

// This is already allowed by the type system
ilist.Add(new int[] { 1, 2, 3 });

// This is actually an array! Not a List<>
List<int> first = list[0];

您可以使用IReadOnlyList&lt;&gt; 来满足您的要求。由于它是只读的,因此该类型错误无法在代码中体现。但是您永远不能在外部列表中添加元素或更新值。泛型接口的这一特性称为“协方差”。

IReadOnlyList<IList<int>> ilist = list;

【讨论】:

  • 谢谢。但是,函数签名要求我需要返回 IList>,而在函数内部,我确实需要将项目添加到列表中以构造它(因此我不能将其设为只读)。有什么办法吗?
  • @breezeZ:如果你愿意制作一个新的清单,有很多方法可以做到这一点。一方面,您可以在最终的ilist 上致电.ToList() 并获得您想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 2011-07-01
  • 1970-01-01
相关资源
最近更新 更多