Stack.Peek()方法用于从堆栈中删除所有对象。
语法:
void Stack.Clear();
参数:无
返回值: void –不返回任何内容。
示例
declare and initialize a stack: Stack stk = new Stack(); insertting elements: stk.Push(100); stk.Push(200); stk.Push(300); stk.Push(400); stk.Push(500); clearing all objects/elements: stk.Clear(); Output: None
using System;
using System.Text;
using System.Collections;
namespace Test
{
class Program
{
//打印堆栈元素的功能
static void printStack(Stack s)
{
foreach (Object obj in s)
{
Console.Write(obj + " ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
//声明并初始化堆栈
Stack stk = new Stack();
//插入元素
stk.Push(100);
stk.Push(200);
stk.Push(300);
stk.Push(400);
stk.Push(500);
Console.WriteLine("Total number of objects in the stack: " + stk.Count);
//打印堆栈元素
Console.WriteLine("Stack elements are...");
printStack(stk);
//清除所有对象/元素
stk.Clear();
Console.WriteLine("Total number of objects in the stack: " + stk.Count);
//按ENTER退出
Console.ReadLine();
}
}
}输出结果
Total number of objects in the stack: 5 Stack elements are... 500 400 300 200 100 Total number of objects in the stack: 0
参考:Stack.Clear方法