简体   繁体   English

C# 从列表转换<List<int> &gt; 到 IList <IList<int> &gt;

[英]C# Conversion from List<List<int>> to IList<IList<int>>

I have a C# function like this-我有一个像这样的 C# 函数-

public IList<IList<int>> Subsets(int[] nums)
{
    List<List<int>> output = new List<List<int>>();
    if (nums.Length == 0)
    {
        return output;    //Problem in this line
        //return null;
    }
    ........
    ........
    return output.Concat(Subsets(nums.Skip(1).ToArray())).ToList();
}

What I am finding is-我发现的是——

Severity    Code    Description Project File    Line    Suppression State

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?) LeetCode    D:\LeetCode\Solution.cs 13  Active

错误

Can anyone please help?有人可以帮忙吗?

Try this:尝试这个:

IList<IList<int>> list2 = list.Cast<IList<int>>().ToList();

You have to add using System.Linq;您必须using System.Linq;添加using System.Linq; for that.为了那个原因。

Change改变

List<List<int>> output = new List<List<int>>();

to

List<IList<int>> output = new List<IList<int>>();

You can cast the outer list to IList, since List implements IList, but you can't force the cast of the type argument of List, so it should be declared as IList since the beginning.您可以将外部列表强制转换为 IList,因为 List 实现了 IList,但您不能强制强制转换 List 的类型参数,因此应从一开始就将其声明为 IList。

Thanks to @NetMage for the great comment.感谢@NetMage的精彩评论。

I have changed我变了

return new List<List<int>>();

to

return new List<IList<int>>();

Which works great for me.这对我很有用。

Though, I agree with other answers to create appropriate interface, you can do this without creating new list like Gur Galler proposed with a little bit of hardcore hacking:虽然,我同意创建适当界面的其他答案,但您可以在不创建像Gur Galler提出的新列表的情况下执行此操作,并进行一些硬核黑客攻击:

[StructLayout(LayoutKind.Explicit)]
public struct Union
{
    [FieldOffset(0)]
    public List<List<int>> a;
    [FieldOffset(0)]
    public IList<IList<int>> b;

    public static IList<IList<int>> Cast(List<List<int>> list)
    {
        var u = new Union();
        u.a = list;
        return u.b;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var lists = new List<List<int>>() { new List<int>() { 1, 2, 3 } };
        IList<IList<int>> casted = Union.Cast(lists);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM