此方法(位於System.Collections命名空間下)用於將Stack複製到現有的一維數組,該數組從指定的數組索引開始。元素將按照後進先出(LIFO)的順序複製到數組中,類似於連續調用Pop所返回的元素的順序。此方法是O(n)運算,其中n是Count。
用法:
public void CopyTo (T[] array, int arrayIndex);
參數:
- array: 一維數組是從Stack複製的元素的目的地。數組必須具有從零開始的索引。
- arrayIndex: 它是數組中從零開始的索引,複製從該索引開始。
異常:
- ArgumentNullException:如果數組為null。
- ArgumentOutOfRangeException:如果索引小於零。
- ArgumentException:如果數組是多維數組,或者源堆棧中的元素數大於從索引到目標數組末尾的可用空間。
- InvalidCastException:如果無法將源Stack的類型強製轉換為目標數組的類型。
下麵給出了一些示例,以更好地理解實現:
示例1:
// C# code to illustrate the
// Stack.CopyTo() 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");
// Creating a string array arr
string[] arr = new string[myStack.Count];
// Copying the elements of
// stack into array arr
myStack.CopyTo(arr, 0);
// Displaying the elements
// in array arr
foreach(string str in arr)
{
Console.WriteLine(str);
}
}
}
輸出:
GeeksforGeeks Data Structures Noida Geeks Classes Geeks
示例2:
// C# code to illustrate the
// Stack.CopyTo() 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);
// Creating an Integer array arr
int[] arr = new int[myStack.Count];
// Copying the elements of
// stack into array arr
myStack.CopyTo(arr, 0);
// Displaying the elements
// in array arr
foreach(int i in arr)
{
Console.WriteLine(i);
}
}
}
輸出:
6 5 4 3 2
參考:
相關用法
- C# Dictionary.Add()用法及代碼示例
- C# Queue.Contains()用法及代碼示例
- C# Math.Abs()函數用法及代碼示例
- C# Stack.Contains()用法及代碼示例
- C# Math.Exp()用法及代碼示例
- C# Math.Abs()方法用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Stack.CopyTo() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。