此方法(位于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#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。