首页 > 编程语言 > 详细

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

时间:2019-04-03 20:04:26      阅读:155      评论:0      收藏:0      [点我收藏+]

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);
            }

        }

 

 

 

 

 

 

 

 

 

 

 

 

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

原文:https://www.cnblogs.com/chucklu/p/10651086.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!