此方法(位於System.Collections命名空間下)用於在Stack的頂部插入一個對象。如果Count已經等於容量,則通過自動重新分配內部數組來增加堆棧的容量,並在添加新元素之前將現有元素複製到新數組。如果Count小於堆棧的容量,則Push是O(1)運算。如果需要增加容量以容納新元素,則Push變為O(n)操作,其中n為Count。
用法:
public virtual void Push (object obj);
例:
// C# code to demonstrate the
// Stack.Push() 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("one");
// Displaying the count of elements
// contained in the Stack
Console.Write("Total number of elements "+
"in the Stack are : ");
Console.WriteLine(myStack.Count);
myStack.Push("two");
// Displaying the count of elements
// contained in the Stack
Console.Write("Total number of elements"+
" in the Stack are : ");
Console.WriteLine(myStack.Count);
myStack.Push("three");
// Displaying the count of elements
// contained in the Stack
Console.Write("Total number of elements"+
" in the Stack are : ");
Console.WriteLine(myStack.Count);
myStack.Push("four");
// Displaying the count of elements
// contained in the Stack
Console.Write("Total number of elements"+
" in the Stack are : ");
Console.WriteLine(myStack.Count);
myStack.Push("five");
// Displaying the count of elements
// contained in the Stack
Console.Write("Total number of elements"+
" in the Stack are : ");
Console.WriteLine(myStack.Count);
myStack.Push("six");
// Displaying the count of elements
// contained in the Stack
Console.Write("Total number of elements"+
" in the Stack are : ");
Console.WriteLine(myStack.Count);
}
}
輸出:
Total number of elements in the Stack are : 1 Total number of elements in the Stack are : 2 Total number of elements in the Stack are : 3 Total number of elements in the Stack are : 4 Total number of elements in the Stack are : 5 Total number of elements in the Stack are : 6
參考:
相關用法
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Stack.Push() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。