Appearance
Stack
Stack 是什么
Stack<T> 是“栈”,特点是:后进先出,英文叫 LIFO,Last In, First Out。
你可以把它想象成一摞盘子:最后放上去的盘子,最先被拿走。
c
using System.Collections.Generic;
Stack<string> states = new Stack<string>();
states.Push("Menu");
states.Push("Game");
states.Push("Pause");
Debug.Log(states.Pop()); // Pause
Debug.Log(states.Pop()); // Game
Debug.Log(states.Pop()); // Menu核心操作
Push:压入栈顶。 Pop:取出并移除栈顶。 Peek:查看栈顶,但不移除。 Count:当前有几个元素。 Clear:清空栈。
c
Stack<int> stack = new();
stack.Push(10);
stack.Push(20);
int top = stack.Peek(); // 20,还在栈里
int outOne = stack.Pop(); // 20,被移除了一定要防空栈
空栈直接 Pop() 或 Peek() 会报错。
c
if (stack.Count > 0)
{
int value = stack.Pop();
}如果你的 Unity / .NET 版本支持,可以用更安全的:
c
if (stack.TryPop(out int value))
{
Debug.Log(value);
}Unity 里常见用法
撤销系统最适合用 Stack,因为最近做的操作,应该最先撤销。
c
using System;
using System.Collections.Generic;
using UnityEngine;
public class UndoExample : MonoBehaviour
{
private Stack<Action> undoStack = new();
public void MoveObject(Transform target, Vector3 newPos)
{
Vector3 oldPos = target.position;
target.position = newPos;
undoStack.Push(() =>
{
target.position = oldPos;
});
}
public void Undo()
{
if (undoStack.TryPop(out Action undo))
{
undo.Invoke();
}
}
}Stack vs Queue vs List
Stack<T>:后进先出,适合撤销、回溯、状态栈。 Queue<T>:先进先出,适合任务队列、消息队列、对象池。 List<T>:按下标访问,适合遍历、排序、随机访问。
常见坑
Stack 没有 stack[0] 这种下标访问。 foreach 遍历时不要 Push 或 Pop 当前栈。 需要处理并移除所有元素时,用 while + Pop。
参考链接Microsoft StackStack.PushStack.PopStack.PeekStack.TryPopMicrosoft QueueUnity Script Serialization Rules