此方法(位於System.Collections命名空間下)用於將Stack複製到新數組。元素將按照後進先出(LIFO)的順序複製到數組中,類似於連續調用Pop所返回的元素的順序。此方法是O(n)運算,其中n是Count。
用法:
public virtual object[] ToArray ();
返回類型:此方法返回一個System.Object類型的新數組,其中包含Stack元素的副本。
下麵給出了一些示例,以更好地理解實現:
示例1:
// C# code to illustrate the 
// Stack.ToArray() 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("Geeks"); 
        myStack.Push("Geeks Classes"); 
        myStack.Push("Noida"); 
        myStack.Push("Data Structures"); 
        myStack.Push("GeeksforGeeks"); 
  
        // Converting the Stack into array 
        Object[] arr = myStack.ToArray(); 
  
        // Displaying the elements in array 
        foreach(Object str in arr) 
        { 
            Console.WriteLine(str); 
        } 
    } 
}
輸出:
GeeksforGeeks Data Structures Noida Geeks Classes Geeks
示例2:
// C# code to illustrate the 
// Stack.ToArray() 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(2); 
        myStack.Push(3); 
        myStack.Push(4); 
        myStack.Push(5); 
        myStack.Push(6); 
  
        // Converting the Stack into array 
        Object[] arr = myStack.ToArray(); 
  
        // Displaying the elements in array 
        foreach(Object i in arr) 
        { 
            Console.WriteLine(i); 
        } 
    } 
}
輸出:
6 5 4 3 2
參考:
- https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.toarray?view=netframework-4.7.2
相關用法
- C# Dictionary.Add()用法及代碼示例
- C# Math.Abs()方法用法及代碼示例
- C# Math.Abs()函數用法及代碼示例
- C# Math.Exp()用法及代碼示例
- C# Queue.Contains()用法及代碼示例
- C# Stack.Pop()用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Stack.ToArray() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
