小编Luk*_*Ith的帖子

Stack <T>中的意外操作顺序与一个衬管有关

通过调用Push()Pop()实例Stack<T>在一行中我得到比在两行执行恕我直言相同的代码不同的行为.

以下代码段重现了该行为:

static void Main(string[] args)
{
 Stack<Element> stack = new Stack<Element>();
 Element e1 = new Element { Value = "one" };
 Element e2 = new Element { Value = "two" };
 stack.Push(e1);
 stack.Push(e2);

 Expected(stack);  // element on satck has value "two"
 //Unexpected(stack);  // element on stack has value "one"

 Console.WriteLine(stack.Peek().Value);
 Console.ReadLine();
}

public static void Unexpected(Stack<Element> stack)
{
 stack.Peek().Value = stack.Pop().Value;
}

public static void Expected(Stack<Element> stack)
{
 Element e = stack.Pop();
 stack.Peek().Value …
Run Code Online (Sandbox Code Playgroud)

c# stack

5
推荐指数
2
解决办法
222
查看次数

标签 统计

c# ×1

stack ×1