You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET中Stack<T>的枚举顺序是否有明确定义?

Does enumerating a Stack<T> have a well-defined order?

Great question—this is one of those cases where the generic collection documentation feels a bit vague, but the actual behavior is consistent and well-defined in practice.

To cut to the chase: Yes, enumerating a Stack<T> follows a clear, predictable order. When you iterate over a stack (whether via foreach, GetEnumerator(), or Stack<T>.Enumerator), you'll get elements starting from the top of the stack (the most recently added item) and moving down to the bottom (the very first item you pushed).

Let's make this concrete with a quick code example:

var stack = new Stack<string>();
stack.Push("First (bottom)");
stack.Push("Second");
stack.Push("Third (top)");

foreach (var item in stack)
{
    Console.WriteLine(item);
}
// Output:
// Third (top)
// Second
// First (bottom)

The confusion comes from the documentation's generic wording about starting "before the first element"—this phrasing is reused across many .NET collections, but for Stack<T>, the "first element" referenced here is the top of the stack. The enumerator is designed to respect the stack's core LIFO (Last-In-First-Out) semantics even during iteration.

This behavior isn't just an implementation detail either—it's been consistent across all .NET versions (Framework, Core, 5+) and is reliable to depend on in your code.

内容的提问来源于stack exchange,提问作者Daniel A. White

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:02:56