无法转换List& lt; List& lt; int& gt;返回类型IList< IList& lt; int& gt; [英] Unable to convert List&lt;List&lt;int&gt;&gt; to return type IList&lt;IList&lt;int&gt;&gt;
问题描述
对于级别顺序遍历,为什么会发生此异常?发生以下异常:
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< 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;返回类型IList< IList& lt; int& gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!