📜  C#中的Stack.Clear方法

📅  最后修改于: 2021-05-30 00:48:27             🧑  作者: Mango

此方法(位于System.Collections命名空间下)用于从堆栈中删除所有对象。此方法会将“堆栈计数”设置为零,并且还会删除对集合元素中其他对象的引用。此方法是O(n)运算,其中n是Count。

句法:

public virtual void Clear ();

下面的程序说明了上面讨论的方法的使用:

范例1:

// C# code to illustrate the
// Stack.Clear Method
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push("1st Element");
        myStack.Push("2nd Element");
        myStack.Push("3rd Element");
        myStack.Push("4th Element");
        myStack.Push("5th Element");
        myStack.Push("6th Element");
  
        // Displaying the count of elements
        // contained in the Stack before
        // removing all the elements
        Console.Write("Total number of elements"+
                         " in the Stack are : ");
  
        Console.WriteLine(myStack.Count);
  
        // Removing all elements from Stack
        myStack.Clear();
  
        // Displaying the count of elements
        // contained in the Stack after
        // removing all the elements
        Console.Write("Total number of elements"+
                         " in the Stack are : ");
  
        Console.WriteLine(myStack.Count);
    }
}
输出:
Total number of elements in the Stack are : 6
Total number of elements in the Stack are : 0

范例2:

// C# code to illustrate the
// Stack.Clear Method
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push(3);
        myStack.Push(5);
        myStack.Push(7);
        myStack.Push(9);
        myStack.Push(11);
  
        // Displaying the count of elements
        // contained in the Stack before
        // removing all the elements
        Console.Write("Total number of elements "+
                           "in the Stack are : ");
  
        Console.WriteLine(myStack.Count);
  
        // Removing all elements from Stack
        myStack.Clear();
  
        // Displaying the count of elements
        // contained in the Stack after
        // removing all the elements
        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

参考:

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