此方法(位于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#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
