为什么我不能为C#中具有IList <IList <int >>返回类型的函数返回List <List <int >>类型的变量

bre*_*zeZ 3 c# interface covariance

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
}
Run Code Online (Sandbox Code Playgroud)

当我直接返回"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?)"
Run Code Online (Sandbox Code Playgroud)

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

rec*_*ive 6

有一个微妙的类型错误.如果这有效,你就有可能遇到这些错误.

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];
Run Code Online (Sandbox Code Playgroud)

您可以通过使用来满足您的要求IReadOnlyList<>.由于它是只读的,因此该类型错误无法在代码中显示.但是你永远不能在外部列表中添加元素或更新值.通用接口的这一特性称为"协方差".

IReadOnlyList<IList<int>> ilist = list;
Run Code Online (Sandbox Code Playgroud)