此方法(位於System.Collections命名空間下)用於獲取Stack中包含的元素數。容量是堆棧可以存儲的元素數量,計數是堆棧中實際存在的元素數量。容量始終大於或等於Count。檢索此屬性的值是O(1)操作。
用法:
public virtual int Count { get; }
返回值:它返回包含在類型為System.Int32的Stack中的元素數。
以下示例程序旨在說明上麵討論的屬性的用法:
範例1:
// C# code illustrate the
// Stack.Count Property
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("Chandigarh");
myStack.Push("Delhi");
myStack.Push("Noida");
myStack.Push("Himachal");
myStack.Push("Punjab");
myStack.Push("Jammu");
// 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:6
範例2:
// C# code illustrate the
// Stack.Count Property
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating a Stack
Stack myStack = new Stack();
// Displaying the count of elements
// contained in the Stack
Console.Write("Total number of elements"+
" in the Stack are:");
// The function should return 0
// as the Stack is empty and it
// doesn't contain any element
Console.WriteLine(myStack.Count);
}
}
輸出:
Total number of elements in the Stack are:0
參考:
相關用法
- C# Dictionary.Item[]用法及代碼示例
- C# SortedDictionary.Values用法及代碼示例
- C# SortedDictionary.Keys用法及代碼示例
- C# SortedDictionary.Count用法及代碼示例
- C# SortedDictionary.Item[]用法及代碼示例
- C# Dictionary.Values用法及代碼示例
- C# Dictionary.Keys用法及代碼示例
- C# Dictionary.Count用法及代碼示例
- C# Queue.Count用法及代碼示例
- C# Queue.IsSynchronized用法及代碼示例
- C# Stack.IsSynchronized用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Stack.Count Property in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。