stack.ToList()–元素顺序? [英] stack.ToList() – order of elements?

查看:148
本文介绍了stack.ToList()–元素顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stack<T>上使用.ToList()扩展方法时,结果是否与弹出每个元素并添加到新列表(与推送内容相反)相同?

如果是这样,是因为这确实是在遍历每个元素,还是将元素内部反向存储并将数组滑入新的List<T>?

解决方案

Stack本身没有ToList方法,它是Enumerable类的扩展方法.由于这些扩展方法仅处理IEnumerable<T>,因此可以安全地假设ToList遍历堆栈中的项以创建新列表(或至少表现得与之完全相同-Enumerable方法有时会测试参数的类型,并使用优化的实现.

有趣的是,文档似乎并未直接说明枚举堆栈的顺序,但是示例代码的确显示了顺序,示例是文档的一部分.另外,在实践中,更改迭代顺序会破坏大量代码,以至于现在更改时风险太大.

我也与Reflector检查过; Stack<T>将其项存储在一个数组中,其最底部的元素的索引为0,但它的Enumerator以相反的顺序迭代数组.因此,从迭代器出来的第一个元素是堆栈的顶部.

When using the .ToList() extension method on a Stack<T>, is the result the same as popping each element and adding to a new list (reverse of what was pushed)?

If so, is this because it really is iterating over each element, or does it store the elements in reverse internally and slip the array into a new List<T>?

解决方案

Stack itself does not have a ToList method, it's the extension method from the Enumerable class. As those extension methods only deal with IEnumerable<T>, it's safe to assume that ToList iterates over the items of the stack to create the new list (or at least acts exactly as if it would - the Enumerable methods sometimes test the type of the argument and use an optimized implementation).

Interestingly the documentation does not seem to directly state which order the stack is enumerated in, but the example code does show an order and the examples are part of the documentation. Also, in practice changing the iteration order would break so much code that it would be way too risky to change now.

I also checked with Reflector; Stack<T> stores its items in an array with the bottommost element at index 0, but its Enumerator iterates the array in reverse order. Therefore the first element that comes out of the iterator is the top of the stack.

这篇关于stack.ToList()–元素顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆