无法转换List< List< int>>.返回类型IList< IList< int>&gt

编程入门 行业动态 更新时间:2024-10-28 16:27:39
本文介绍了无法转换List< List< int>>.返回类型IList< IList< int>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于级别顺序遍历,为什么会发生此异常? 发生以下异常:

For level order traversal why does this exception occur? Following exception occurs:

无法将类型'System.Collections.Generic.List<System.Collections.Generic.List<int>>'隐式转换为'System.Collections.Generic.IList<System.Collections.Generic.IList<int>>'.存在显式转换(您是否缺少演员表?)

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?)

public IList<IList<int>> LevelOrder(TreeNode root) { var result = new List<List<int>>(); var que = new Queue<TreeNode>(); //if(root==null) return result; que.Enqueue(root); while(que.Count!=0) { int n = que.Count; var subList = new List<int>(); for(int i=0;i<n;i++) { if(que.Peek().left!=null) que.Enqueue(que.Peek().left); if(que.Peek().right!=null) que.Enqueue(que.Peek().right); subList.Add(que.Dequeue().val); } result.Add(subList); } return result; }

推荐答案

只需将结果的声明更改为List<IList<int>>.

Just change the declaration of your result to List<IList<int>>.

List<T>实现IList<T>,但是List<List<T>>不实现IList<IList<int>>.除非以这种方式定义,否则通用参数不是协变或协变的,而IList<T>则不是,因此类型必须完全匹配.

List<T> implements IList<T>, but List<List<T>> does not implement IList<IList<int>>. Generic parameters are not covariant or contravariant unless defined that way and IList<T> is not, so the type must match exactly.

public IList<IList<int>> LevelOrder(TreeNode root) { var result = new List<IList<int>>(); var que = new Queue<TreeNode>(); //if(root==null) return result; que.Enqueue(root); while (que.Count != 0) { int n = que.Count; var subList = new List<int>(); for (int i = 0; i < n; i++) { if (que.Peek().left != null) que.Enqueue(que.Peek().left); if (que.Peek().right != null) que.Enqueue(que.Peek().right); subList.Add(que.Dequeue().val); } result.Add(subList); } return result; }

更多推荐

无法转换List&lt; List&lt; int&gt;&gt;.返回类型IList&lt; IList&lt

本文发布于:2023-09-23 12:12:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   lt   amp   List   IList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!