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

        }
复制代码

 

 

 

 

 

 

 

 

 

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(153)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-04-03 outlook创建收信规则,将收到的所有邮件,转发到qq邮箱,然后删除
2018-04-03 everything的使用
2018-04-03 log4net preserveLogFileNameExtension 和 watch
点击右上角即可分享
微信分享提示