📜  在C#中从堆栈顶部删除对象

📅  最后修改于: 2021-05-29 16:04:02             🧑  作者: Mango

Stack .Pop方法用于删除并返回Stack 顶部的对象。此方法位于System.Collections.Generic命名空间下。

句法:

public T Pop ();

返回值:它返回要从堆栈顶部移除的对象。

异常:如果Stack 为空,则此方法将提供InvalidOperationException。

下面的程序说明了上述方法的用法:

范例1:

// C# Program to illustrate the
// use of Stack.Pop() Method
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // Creating a Stack of Strings
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push("Geeks");
        myStack.Push("Geeks Classes");
        myStack.Push("Noida");
        myStack.Push("Data Structures");
        myStack.Push("GeeksforGeeks");
  
        Console.WriteLine("Number of elements in the Stack: {0}",
                                                 myStack.Count);
  
        // Retrieveing top element of Stack
        Console.Write("Top element of Stack is: ");
        Console.Write(myStack.Pop());
  
        // printing the no of Stack element
        // after Pop operation
        Console.WriteLine("\nNumber of elements in the Stack: {0}",
                                                    myStack.Count);
    }
}
输出:
Number of elements in the Stack: 5
Top element of Stack is: GeeksforGeeks
Number of elements in the Stack: 4

范例2:

// C# Program to illustrate the
// use of Stack.Pop() Method
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
  
        // Creating a Stack of integers
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push(7);
        myStack.Push(9);
  
        Console.WriteLine("Number of elements in the Stack: {0}",
                                                  myStack.Count);
  
        // Retrieveing top element of Stack
        Console.Write("Top element of Stack is: ");
        Console.Write(myStack.Pop());
  
        // printing the no of Stack element
        // after Pop operation
        Console.WriteLine("\nNumber of elements in the Stack: {0}",
                                                    myStack.Count);
    }
}
输出:
Number of elements in the Stack: 2
Top element of Stack is: 9
Number of elements in the Stack: 1

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.stack-1.pop?view=netframework-4.7.2