Why there is two completely different version of Reverse for List and IEnumerable?

https://stackoverflow.com/questions/12390971/why-there-is-two-completely-different-version-of-reverse-for-list-and-ienumerabl

It is worth noting that the list method is a lot older than the extension method. The naming was likely kept the same as Reverse seems more succinct简洁的 than BackwardsIterator.

If you want to bypass the list version and go to the extension method, you need to treat the list like an IEnumerable<T>:

var numbers = new List<int>();
numbers.Reverse(); // hits list
(numbers as IEnumerable<int>).Reverse(); // hits extension

Or call the extension method as a static method:

Enumerable.Reverse(numbers);

Note that the Enumerable version will need to iterate the underlying enumerable entirely in order to start iterating it in reverse. If you plan on doing this multiple times over the same enumerable, consider permanently reversing the order and iterating it normally.

 

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.reverse?view=netframework-4.7.2  List<T>.Reverse

这个方法直接操作了源数据

 

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.reverse?view=netframework-4.7.2    Enumerable.Reverse(IEnumerable<TSource>) 

这个方法不操作源数据,会返回结果

public static System.Collections.Generic.IEnumerable<TSource> Reverse<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

 

    [Test]
        public void ReverseTest()
        {
            List<int> list = new List<int>() {1, 2, 3};
            list.Reverse();
            foreach (var item in list)
            {
                Console.WriteLine(item);
            }

            IEnumerable<int> test = list;
            test.Reverse();
            foreach (var item in list)
            {
                Console.WriteLine(item);
            }

        }

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2019-04-03 19:54  ChuckLu  阅读(153)  评论(0编辑  收藏  举报