C# 堆栈 - Clear() 方法
C# 堆栈 Clear() 方法用于清空堆栈,方法是移除堆栈中的所有元素。
执行此方法时,计数会被设置为零,并且对集合元素中其他对象的引用也会被释放。这需要 O(n) 的时间复杂度,其中 n 是计数。
语法
以下是 C# 堆栈 Clear() 方法的语法 -
public virtual void Clear ();
参数
此方法不接受任何参数。
返回值
此方法不返回任何值。
示例 1:在 Stack 中使用 Clear() 方法
以下是使用 Clear() 方法清空堆栈的基本示例 -
using System;
using System.Collections;
class Example {
public static void Main() {
Stack myStack = new Stack();
// 将元素插入到堆栈中
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
myStack.Push(5);
Console.Write("Total number of elements in the Stack are: ");
Console.WriteLine(myStack.Count);
// 从 Stack 中移除所有元素
myStack.Clear();
Console.Write("Total number of elements in the Stack are: ");
Console.WriteLine(myStack.Count);
}
}
输出
以下是输出 -
Total number of elements in the Stack are: 5 Total number of elements in the Stack are: 0
示例 2:清除堆栈中的所有字符串
让我们看另一个使用 Clear() 方法清除堆栈中所有字符串的示例 -
using System;
using System.Collections;
class Example {
public static void Main() {
Stack myStack = new Stack();
// 将元素插入到堆栈中
myStack.Push("Hello");
myStack.Push("tutorialspoint");
myStack.Push("India");
myStack.Push("Good to know");
Console.Write("Total number of elements in the Stack are: ");
Console.WriteLine(myStack.Count);
// 从 Stack 中移除所有元素
myStack.Clear();
Console.Write("Total number of elements in the Stack are: ");
Console.WriteLine(myStack.Count);
}
}
输出
以下是输出 -
Total number of elements in the Stack are: 4 Total number of elements in the Stack are: 0
示例 3:从堆栈中清除 Person 对象
以下示例创建了一个 Person 对象。这里,我们使用 Clear() 方法清除 Person 对象中的所有 Person 详细信息 -
using System;
using System.Collections.Generic;
class Person {
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age) {
Name = name;
Age = age;
}
public override string ToString() {
return $"Name: {Name}, Age: {Age}";
}
}
class Example {
static void Main() {
// 创建一个 Person 对象堆栈
Stack<Person> people = new Stack<Person>();
// 将 Person 对象推送到堆栈
people.Push(new Person("Aman", 25));
people.Push(new Person("Gupta", 24));
people.Push(new Person("Vivek", 26));
Console.WriteLine("People stack before Clear:");
foreach (var person in people) {
Console.WriteLine(person);
}
// 清除堆栈
people.Clear();
Console.WriteLine("People stack after Clear:");
Console.WriteLine("Is Empty? " + (people.Count == 0 ? "Yes" : "No"));
}
}
输出
以下是输出 -
People stack before Clear: Name: Vivek, Age: 26 Name: Gupta, Age: 24 Name: Aman, Age: 25 People stack after Clear: Is Empty? Yes

csharp_stack.html