此方法(位于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/zh-cn/dotnet/api/system.collections.stack.toarray?view=netframework-4.7.2