堆叠式和LT;>在C#实现 [英] Stack<> implementation in C#

查看:134
本文介绍了堆叠式和LT;>在C#实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在执行一个递归目录搜索实现,我使用堆栈跟踪路径元素。当我用的string.join()加入了路径元素,我发现他们被逆转。当我调试的方法,我看着堆,发现自己的协议栈的内部数组中被逆转的元素,即最近一次推()的元素是在内部数组的开始,最近最少推() ED的因素是在内部数组的末尾。这似乎屁股向后,非常反直觉。谁能告诉我,为什么微软会实现这样的方式堆叠?

I've recently been implementing a recursive directory search implementation and I'm using a Stack to track the path elements. When I used string.Join() to join the path elements, I found that they were reversed. When I debugged the method, I looked into the stack and found that the elements themselves were reversed in the Stack's internal array, ie the most recently Push()ed element was at the beginning of the internal array, and the least recently Push()ed element was at the end of the internal array. This seems ass-backward and very counter-intuitive. Can somebody please tell me why Microsoft would implement a stack in such a manner ?

推荐答案

我想你搞错了。

这并不是说堆栈< T> .Push 内部在其内部数组的开始插入一个项目(它不)。相反,它从顶部到底部列举,因为这是其中一个会直觉地通过烟囱枚举的方式(想想煎饼一叠的:你开始在顶部和工作下来自己的方式)

It isn't that Stack<T>.Push internally inserts an item at the start of its internal array (it doesn't). Rather, it enumerates from the top to the bottom, as this is the manner in which one would intuitively enumerate through a stack (think of a stack of pancakes: you start at the top and work your way down).

如果您从Visual Studio的调试器中看到一个集合的内容,我认为它会在他们列举的顺序它们显示给你 - 他们正在内部存储的顺序*

If you look at the contents of a collection from within Visual Studio's debugger, I think it will display them to you in the order they're enumerated -- not the order they're stored internally*.

看看在堆栈< T>在的方法: //www.red-gate.com/products/reflector/\">Reflector ,你会看到代码是你所期望基本上是什么:

Take a look at the Stack<T>.Push method in Reflector and you'll see that the code is basically exactly what you'd expect:

// (code to check array size)
this._array[this._size++] = item;
// (code to update internal version number)



因此堆栈在内部增加了新的元素到其内部数组的末尾。这是堆栈< T>这是把你迷惑.Enumerator 类,而不是堆栈< T> 类本身

<子> *我不知道这是否是一般的事实,但它堆栈< T> ;看到汉斯帕桑特的出色答卷为什么的原因。

*I don't know whether this is true in general, but it's true for Stack<T>; see Hans Passant's excellent answer for the reason why.

这篇关于堆叠式和LT;&GT;在C#实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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