Stack<T>.Peek Metodo

Definizione

Viene restituito l'oggetto all'inizio dello Stack<T> senza rimuoverlo.Returns the object at the top of the Stack<T> without removing it.

public:
 T Peek();
public T Peek ();
member this.Peek : unit -> 'T
Public Function Peek () As T

Restituisce

T

Oggetto all'inizio dell'oggetto Stack<T>.The object at the top of the Stack<T>.

Eccezioni

La classe Stack<T> è vuota.The Stack<T> is empty.

Esempio

Nell'esempio di codice seguente vengono illustrati diversi metodi della Stack<T> classe generica, incluso il Peek metodo.The following code example demonstrates several methods of the Stack<T> generic class, including the Peek method.

Nell'esempio di codice viene creato uno stack di stringhe con la capacità predefinita e viene utilizzato il Push metodo per effettuare il push di cinque stringhe nello stack.The code example creates a stack of strings with default capacity and uses the Push method to push five strings onto the stack. Gli elementi dello stack vengono enumerati, che non modifica lo stato dello stack.The elements of the stack are enumerated, which does not change the state of the stack. Il Pop metodo viene utilizzato per estrarre la prima stringa dallo stack.The Pop method is used to pop the first string off the stack. Il Peek metodo viene usato per esaminare l'elemento successivo nello stack, quindi il Pop metodo viene usato per estrarlo.The Peek method is used to look at the next item on the stack, and then the Pop method is used to pop it off.

Il ToArray metodo viene usato per creare una matrice e copiarvi gli elementi dello stack, quindi la matrice viene passata al Stack<T> costruttore che accetta IEnumerable<T> , creando una copia dello stack con l'ordine degli elementi invertiti.The ToArray method is used to create an array and copy the stack elements to it, then the array is passed to the Stack<T> constructor that takes IEnumerable<T>, creating a copy of the stack with the order of the elements reversed. Vengono visualizzati gli elementi della copia.The elements of the copy are displayed.

Viene creata una matrice per due volte la dimensione dello stack e il CopyTo metodo viene usato per copiare gli elementi della matrice a partire dal centro della matrice.An array twice the size of the stack is created, and the CopyTo method is used to copy the array elements beginning at the middle of the array. Il Stack<T> costruttore viene nuovamente utilizzato per creare una copia dello stack con l'ordine degli elementi invertiti; pertanto, i tre elementi null si trovano alla fine.The Stack<T> constructor is used again to create a copy of the stack with the order of elements reversed; thus, the three null elements are at the end.

Il Contains metodo viene utilizzato per indicare che la stringa "quattro" si trova nella prima copia dello stack, dopo la quale il Clear metodo cancella la copia e la Count proprietà indica che lo stack è vuoto.The Contains method is used to show that the string "four" is in the first copy of the stack, after which the Clear method clears the copy and the Count property shows that the stack is empty.

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

Commenti

Questo metodo è analogo al metodo Pop, ma Peek non modifica la Stack<T>.This method is similar to the Pop method, but Peek does not modify the Stack<T>.

Se T il tipo è un tipo di riferimento, è null possibile effettuare il push su Stack<T> come segnaposto, se necessario.If type T is a reference type, null can be pushed onto the Stack<T> as a placeholder, if needed.

Questo metodo è un'operazione O (1).This method is an O(1) operation.

Si applica a

Vedi anche