此方法(位于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
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.stack.count?view=netframework-4.7.2