Stack<T>.Count Propriété

Définition

Obtient le nombre d’éléments contenus dans le Stack<T>.

public:
 property int Count { int get(); };
public int Count { get; }
member this.Count : int
Public ReadOnly Property Count As Integer

Valeur de propriété

Int32

Nombre d'éléments contenus dans Stack<T>.

Implémente

Exemples

L’exemple de code suivant illustre plusieurs propriétés et méthodes de la Stack<T> classe générique, y compris la Count propriété.

L’exemple de code crée une pile de chaînes avec une capacité par défaut et utilise la Push méthode pour envoyer cinq chaînes sur la pile. Les éléments de la pile sont énumérés, ce qui ne modifie pas l’état de la pile. La Pop méthode est utilisée pour pop the first string off the stack. La Peek méthode est utilisée pour examiner l’élément suivant sur la pile, puis la Pop méthode est utilisée pour la désactiver.

La ToArray méthode est utilisée pour créer un tableau et copier les éléments de pile dans celui-ci, puis le tableau est passé au Stack<T> constructeur qui IEnumerable<T>prend , créant une copie de la pile avec l’ordre des éléments inversés. Les éléments de la copie sont affichés.

Un tableau deux fois la taille de la pile est créée, et la CopyTo méthode est utilisée pour copier les éléments de tableau commençant au milieu du tableau. Le Stack<T> constructeur est utilisé de nouveau pour créer une copie de la pile avec l’ordre des éléments inversés ; ainsi, les trois éléments null sont à la fin.

La Contains méthode est utilisée pour montrer que la chaîne « quatre » se trouve dans la première copie de la pile, après laquelle la Clear méthode efface la copie et la propriété indique que la Count pile est vide.

using System;
using System.Collections.Generic;

class Example
{
    public static void Main()
    {
        Stack<string> numbers = new Stack<string>();
        numbers.Push("one");
        numbers.Push("two");
        numbers.Push("three");
        numbers.Push("four");
        numbers.Push("five");

        // A stack can be enumerated without disturbing its contents.
        foreach( string number in numbers )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nPopping '{0}'", numbers.Pop());
        Console.WriteLine("Peek at next item to destack: {0}",
            numbers.Peek());
        Console.WriteLine("Popping '{0}'", numbers.Pop());

        // Create a copy of the stack, using the ToArray method and the
        // constructor that accepts an IEnumerable<T>.
        Stack<string> stack2 = new Stack<string>(numbers.ToArray());

        Console.WriteLine("\nContents of the first copy:");
        foreach( string number in stack2 )
        {
            Console.WriteLine(number);
        }

        // Create an array twice the size of the stack and copy the
        // elements of the stack, starting at the middle of the
        // array.
        string[] array2 = new string[numbers.Count * 2];
        numbers.CopyTo(array2, numbers.Count);

        // Create a second stack, using the constructor that accepts an
        // IEnumerable(Of T).
        Stack<string> stack3 = new Stack<string>(array2);

        Console.WriteLine("\nContents of the second copy, with duplicates and nulls:");
        foreach( string number in stack3 )
        {
            Console.WriteLine(number);
        }

        Console.WriteLine("\nstack2.Contains(\"four\") = {0}",
            stack2.Contains("four"));

        Console.WriteLine("\nstack2.Clear()");
        stack2.Clear();
        Console.WriteLine("\nstack2.Count = {0}", stack2.Count);
    }
}

/* This code example produces the following output:

five
four
three
two
one

Popping 'five'
Peek at next item to destack: four
Popping 'four'

Contents of the first copy:
one
two
three

Contents of the second copy, with duplicates and nulls:
one
two
three




stack2.Contains("four") = False

stack2.Clear()

stack2.Count = 0
 */
Imports System.Collections.Generic

Module Example

    Sub Main

        Dim numbers As New Stack(Of String)
        numbers.Push("one")
        numbers.Push("two")
        numbers.Push("three")
        numbers.Push("four")
        numbers.Push("five")

        ' A stack can be enumerated without disturbing its contents.
        For Each number As String In numbers
            Console.WriteLine(number)
        Next

        Console.WriteLine(vbLf & "Popping '{0}'", numbers.Pop())
        Console.WriteLine("Peek at next item to pop: {0}", _
            numbers.Peek())    
        Console.WriteLine("Popping '{0}'", numbers.Pop())

        ' Create another stack, using the ToArray method and the
        ' constructor that accepts an IEnumerable(Of T). Note that
        ' the order of items on the new stack is reversed.
        Dim stack2 As New Stack(Of String)(numbers.ToArray())

        Console.WriteLine(vbLf & "Contents of the first copy:")
        For Each number As String In stack2
            Console.WriteLine(number)
        Next
        
        ' Create an array twice the size of the stack, compensating
        ' for the fact that Visual Basic allocates an extra array 
        ' element. Copy the elements of the stack, starting at the
        ' middle of the array. 
        Dim array2((numbers.Count * 2) - 1) As String
        numbers.CopyTo(array2, numbers.Count)
        
        ' Create a second stack, using the constructor that accepts an
        ' IEnumerable(Of T). The elements are reversed, with the null
        ' elements appearing at the end of the stack when enumerated.
        Dim stack3 As New Stack(Of String)(array2)

        Console.WriteLine(vbLf & _
            "Contents of the second copy, with duplicates and nulls:")
        For Each number As String In stack3
            Console.WriteLine(number)
        Next

        Console.WriteLine(vbLf & "stack2.Contains(""four"") = {0}", _
            stack2.Contains("four"))

        Console.WriteLine(vbLf & "stack2.Clear()")
        stack2.Clear()
        Console.WriteLine(vbLf & "stack2.Count = {0}", _
            stack2.Count)
    End Sub
End Module

' This code example produces the following output:
'
'five
'four
'three
'two
'one
'
'Popping 'five'
'Peek at next item to pop: four
'Popping 'four'
'
'Contents of the first copy:
'one
'two
'three
'
'Contents of the second copy, with duplicates and nulls:
'one
'two
'three
'
'
'
'
'stack2.Contains("four") = False
'
'stack2.Clear()
'
'stack2.Count = 0

Remarques

La capacité du Stack<T> fichier est le nombre d’éléments que le Stack<T> magasin peut stocker. Count est le nombre d’éléments qui sont en fait dans le Stack<T>.

La capacité est toujours supérieure ou égale à Count. Si Count elle dépasse la capacité lors de l’ajout d’éléments, la capacité est augmentée en réaffectant automatiquement le tableau interne avant de copier les anciens éléments et d’ajouter les nouveaux éléments.

La récupération de la valeur de cette propriété est une opération O(1).

S’applique à