此方法(位於System.Collections命名空間下)用於刪除並返回堆棧頂部的對象。此方法與Peek方法相似,但是Peek不會修改堆棧。
用法:
public virtual object Pop ();
返回值:它返回從堆棧頂部刪除的對象。
異常:如果堆棧為空,則此方法將提供InvalidOperationException。
以下示例程序旨在說明上述方法的用法:
示例1:
// C# Program to illustrate the
// use of Stack.Pop() Method
using System;
using System.Collections;
class GFG {
// Main Method
public static void Main()
{
// Creating a Stack
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;
class GFG {
// Main Method
public static void Main()
{
// Creating a Stack
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
參考:
相關用法
- C# Stack.Contains()用法及代碼示例
- C# Dictionary.Add()用法及代碼示例
- C# Math.Abs()函數用法及代碼示例
- C# DateTime.Add()用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Stack.Pop() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。