首页 > 解决方案 > 无法转换 IList列出

问题描述

这是我的函数签名:

public IList<IList<int>> LevelOrder(TreeNode root)

这是显示我如何创建IList<IList<int>>从函数返回的代码片段:

IList<IList<int>> result = new List<List<int>>();
        result.Add(new List<int>());
        while (completeQueue.Count != 0)
        {
            current = completeQueue.Dequeue();
            if (level != current.level)
            {
                result.Add(new List<int>());
                level = current.level;
            }
            result[level].Add(current.node.val);
        }

        return result;

当我运行这个函数时,我从最后一行 ( return result) 中得到一个错误: Line 49: Char 36: error CS0266: 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?) (in Solution.cs)

List实现IList接口。为什么这不起作用?

标签: c#listgenerics

解决方案


您返回 aIList<List<int>>而不是 a IList<IList<int>>

这不是同一类型,因为您的List<List<int>>工具IList<List<int>>不是IList<IList<int>>

你应该使用:

var result = new List<IList<int>>();

推荐阅读