为什么 IList<>.Reverse() 不像 List<>().Reverse 那样工作
我对 List
和 Reverse(this IEnumerable
有问题。
看代码:
// Part 1
List<int> list = new List<int> { 1, 2, 3 };
foreach (int x in list)
Console.Write(x);
Console.WriteLine();
list.Reverse();
foreach (int x in list)
Console.Write(x);
Console.WriteLine();
list.Reverse();
// Part2
IList<int> ilist = list;
foreach (int x in list)
Console.Write(x);
Console.WriteLine();
ilist.Reverse();
foreach (int x in ilist)
Console.Write(x);
Console.WriteLine();
ilist.Reverse();
我的结果:
123
321
123
123
因为Reverse()
-Part1是List
,Reverse()
-Part2是 Reverse(此 IEnumerable
我想在第 2 部分中为 IList
执行 List
。我怎样才能做到呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IList
没有Reverse
方法,因此它使用扩展方法。在IList
引用上使用List.Reverse
的唯一方法是将其强制转换或转换为List
>。仅当您首先确定它确实是一个List
时,转换才会起作用:另一种选择是创建一个
List
来自您的IList
实例,而不是假设它已经是List
:原因 code>Reverse 扩展方法实际上并不影响底层列表,因为它在
IEnumerable
上运行,而该列表不一定是可写的(Enumerable
都不是) code> 扩展方法对原始集合进行更改,它们返回一个新集合)。要使用此版本的
Reverse
,只需使用Reverse
调用的乘积,而不是原始列表:IList<int>
doesn't have aReverse
method, so it uses the extension method. The only way to useList<T>.Reverse
on yourIList<int>
reference is to cast or convert it to aList<int>
. Casting will only work if you're sure that it's really aList<int>
in the first place:Another option would be to create a
List<int>
from yourIList<int>
instance, rather than assuming it already is aList<int>
:The reason that the
Reverse
extension method doesn't actually affect the underlying list is because it operates onIEnumerable<T>
, which isn't necessarily writeable (none of theEnumerable
extension methods make changes to the original collection, they return a new collection).To use this version of
Reverse
, just use the product of theReverse
call, rather than the original list:在第二个示例中,您对
IEnumerable
使用扩展方法,这不会改变原始集合,而是生成一个查询,该查询将导致原始列表的顺序相反命令。也就是说,如果你想利用ilist.Reverse()
的结果,你会说In the second example, you're using an extension method against
IEnumerable<T>
, and this is not mutating the original collection but rather producing a query that would result in a sequence of your original list in reverse order. That is to say, if you want to utilize the results ofilist.Reverse()
, you would say