當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# Stack.Clear用法及代碼示例


此方法(位於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

參考:



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Stack.Clear Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。