转换列表&LT;列表&LT;对象&gt;&GT;到IList的&LT; IList的&LT;对象&gt;&GT; [英] convert List<List<object>> to IList<IList<object>>
问题描述
我写了一个方法,这是
公开名单&LT;列表&LT;对象&gt;&GT;获取(字符串数据)
,
里面创建
名单,其中,名单,其中,对象&gt;&GT; P =新的名单,其中,名单,其中,对象&gt;&GT;();
I have written a method which is
public List<List<object>> Fetch(string data)
,
inside I create
List<List<object>> p = new List<List<object>>();
我的老板现在要返回的IList&LT; IList的&LT;对象&gt;&GT;
而不是名单,其中,名单,其中,对象&gt;&GT;
即
公开的IList&LT; IList的&LT;对象&gt;&GT;获取(字符串数据)
,
my boss now wants to return a IList<IList<object>>
instead of List<List<object>>
ie
public IList<IList<object>> Fetch(string data)
,
所以当我尝试做
收益率(IList的&LT; IList的&LT;对象&gt;&GT;)P; //抛出一个异常
so when I try do
return (IList<IList<object>>) p; //throws an exception
我要如何转换
名单,其中,名单,其中,对象&gt;&gt;至
键,返回的IList&LT
;的IList&LT;对象&gt;&GT; 名单,其中,名单,其中,对象&gt;&GT;
How do I convert
List<List<object>>
to IList<IList<object>>
and back to List<List<object>>
感谢。
推荐答案
您不能执行通过直铸造的转换 - 它不会是安全的。相反,你应该使用:
You can't perform that conversion via straight casting - it wouldn't be safe. Instead, you should use:
IList<IList<object>> ret = new List<IList<object>>();
然后为每个子列表您可以使用:
Then for each "sublist" you can use:
// Or whatever
ret.Add(new List<object>());
最后,只返回 RET
。
您的可以的使用LINQ执行现有的名单,其中的转换;列表&LT;对象&gt;&GT;
当您返回它 - 但它会最好只建立一个更为合适的类型入手,如上图所示。
You could use LINQ to perform the conversion of your existing List<List<object>>
when you return it - but it would be better to just create a more appropriate type to start with, as shown above.
要理解为什么一些现有的答案都错了,假设你的可以的做到这一点:
To understand why some of the existing answers are wrong, suppose you could do this:
IList<IList<object>> p = new List<List<object>>();
那么这将是有效的:
Then this would be valid:
List<List<object>> listOfLists = new List<List<object>>();
IList<IList<object>> p = listOfLists;
p.Add(new object[]);
List<object> list = p[0];
但 P [0]
是一个参考的 [对象]
,不是列表&LT;对象&gt;
...我们所谓的类型安全的code看起来并不安全更多...
But p[0]
is a reference to an object[]
, not a List<object>
... our supposedly type-safe code doesn't look as safe any more...
幸运的是,的IList&LT; T&GT;
是不变的prevent正是这个问题。
Fortunately, IList<T>
is invariant to prevent exactly this problem.
这篇关于转换列表&LT;列表&LT;对象&gt;&GT;到IList的&LT; IList的&LT;对象&gt;&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!