本文介绍了为什么IList<> .Reverse()不能像List<>()那样工作。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到问题列表< T> .Reverse()反向(此IEnumerable< TSource>来源)
查看代码:

I have problem with List<T>.Reverse() and Reverse(this IEnumerable<TSource> source).Look to the code:

  // 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< T> .Reverse() Reverse () -Part2是反向(此IEnumerable< TSource>源)
我想执行 List< int> ; .Reverse()在Part2中为 IList< int> 。我怎么做?

because Reverse()-Part1 is List<T>.Reverse(), Reverse()-Part2 is Reverse(this IEnumerable<TSource> source)I want execute List<int>.Reverse() in Part2 for IList<int>. How I can do it?

推荐答案

IList< int> doesn' t有一个反向方法,因此它使用扩展方法。在 IList< int> 引用中使用 List< T> .Reverse 的唯一方法是转换或转换它到列表< int> 。只有当你确定它首先是 List< int> 时,才能进行投射:

IList<int> doesn't have a Reverse method, so it uses the extension method. The only way to use List<T>.Reverse on your IList<int> reference is to cast or convert it to a List<int>. Casting will only work if you're sure that it's really a List<int> in the first place:

IList<int> abstractList;
var concreteList = (List<int>)abstractList;
concreteList.Reverse();

另一种选择是创建一个 List<来自 IList< int> 实例的; int> ,而不是假设它已经是 List< int>

Another option would be to create a List<int> from your IList<int> instance, rather than assuming it already is a List<int>:

IList<int> abstractList;
var concreteList = new List<int>(abstractList);
concreteList.Reverse();

原因 反向扩展方法实际上并不影响基础列表,因为它在 IEnumerable< T> 上运行,这不一定是可写的(没有 Enumerable 扩展方法对原始集合进行更改,它们返回 new 集合。)

The reason that the Reverse extension method doesn't actually affect the underlying list is because it operates on IEnumerable<T>, which isn't necessarily writeable (none of the Enumerable extension methods make changes to the original collection, they return a new collection).

To使用此版本的 Reverse ,只需使用 Reverse 调用的产品,而不是原始列表:

To use this version of Reverse, just use the product of the Reverse call, rather than the original list:

IList<int> abstractList;
IEnumerable<int> reversedList = abstractList.Reverse();

这篇关于为什么IList&lt;&gt; .Reverse()不能像List&lt;&gt;()那样工作。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:18