Stack<T> Costruttori

Definizione

Inizializza una nuova istanza della classe Stack<T>.

Overload

Stack<T>()

Inizializza una nuova istanza della classe Stack<T> vuota e con capacità iniziale predefinita.

Stack<T>(IEnumerable<T>)

Inizializza una nuova istanza della classe Stack<T> che contiene gli elementi copiati dalla raccolta specificata e ha la capacità sufficiente per contenere il numero di elementi copiati.

Stack<T>(Int32)

Consente l'inizializzazione di una nuova istanza della classe Stack<T>, che è vuota e ha la capacità iniziale maggiore tra quella specificata e quella predefinita.

Stack<T>()

Source:
Stack.cs
Source:
Stack.cs
Source:
Stack.cs

Inizializza una nuova istanza della classe Stack<T> vuota e con capacità iniziale predefinita.

public:
 Stack();
public Stack ();
Public Sub New ()

Esempio

Nell'esempio di codice seguente viene illustrato questo costruttore e diversi metodi della Stack<T> classe generica.

L'esempio di codice crea uno stack di stringhe con capacità predefinita e usa il metodo per eseguire il Push push di cinque stringhe nello stack. Gli elementi dello stack vengono enumerati, che non modificano lo stato dello stack. Il Pop metodo viene usato per estrarre la prima stringa dallo stack. Il Peek metodo viene usato per esaminare l'elemento successivo nello stack e quindi il Pop metodo viene usato per disattivarlo.

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. Vengono visualizzati gli elementi della copia.

Viene creata una matrice due volte la dimensione dello stack e il CopyTo metodo viene usato per copiare gli elementi della matrice a partire dal centro della matrice. Il Stack<T> costruttore viene usato di nuovo per creare una copia dello stack con l'ordine degli elementi invertiti, quindi i tre elementi Null si trovano alla fine.

Il Contains metodo viene usato 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.

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
 */
open System
open System.Collections.Generic

let numbers = Stack()
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 number in numbers do
    printfn $"{number}"

printfn $"\nPopping '{numbers.Pop()}'"
printfn $"Peek at next item to destack: {numbers.Peek()}"
numbers.Peek() |> ignore
printfn $"Popping '{numbers.Pop()}'"

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

printfn "\nContents of the first copy:"

for number in stack2 do
    printfn $"{number}"

// Create an array twice the size of the stack and copy the
// elements of the stack, starting at the middle of the
// array.
let array2 = numbers.Count * 2 |> Array.zeroCreate
numbers.CopyTo(array2, numbers.Count)

// Create a second stack, using the constructor that accepts an
// IEnumerable(Of T).
let stack3 = Stack array2

printfn "\nContents of the second copy, with duplicates and nulls:"

for number in stack3 do
    printfn $"{number}"

printfn
    $"""
stack2.Contains "four" = {stack2.Contains "four"}"""

printfn "\nstack2.Clear()"
stack2.Clear()
printfn $"\nstack2.Count = {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

La capacità di un Stack<T> oggetto è il numero di elementi che l'oggetto Stack<T> può contenere. Man mano che gli elementi vengono aggiunti a un Stack<T>oggetto , la capacità viene aumentata automaticamente in base alle esigenze tramite la riallocazione della matrice interna.

Se è possibile stimare le dimensioni della raccolta, specificando la capacità iniziale è possibile eliminare la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Stack<T>di elementi a .

La capacità può essere ridotta chiamando TrimExcess.

Questo costruttore è un'operazione O(1).

Si applica a

Stack<T>(IEnumerable<T>)

Source:
Stack.cs
Source:
Stack.cs
Source:
Stack.cs

Inizializza una nuova istanza della classe Stack<T> che contiene gli elementi copiati dalla raccolta specificata e ha la capacità sufficiente per contenere il numero di elementi copiati.

public:
 Stack(System::Collections::Generic::IEnumerable<T> ^ collection);
public Stack (System.Collections.Generic.IEnumerable<T> collection);
new System.Collections.Generic.Stack<'T> : seq<'T> -> System.Collections.Generic.Stack<'T>
Public Sub New (collection As IEnumerable(Of T))

Parametri

collection
IEnumerable<T>

Raccolta da cui copiare gli elementi.

Eccezioni

collection è null.

Esempio

Nell'esempio di codice seguente viene illustrato questo costruttore e diversi metodi della Stack<T> classe generica.

L'esempio di codice crea uno stack di stringhe con capacità predefinita e usa il metodo per eseguire il Push push di cinque stringhe nello stack. Gli elementi dello stack vengono enumerati, che non modificano lo stato dello stack. Il Pop metodo viene usato per estrarre la prima stringa dallo stack. Il Peek metodo viene usato per esaminare l'elemento successivo nello stack e quindi il Pop metodo viene usato per disattivarlo.

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. Vengono visualizzati gli elementi della copia.

Viene creata una matrice due volte la dimensione dello stack e il CopyTo metodo viene usato per copiare gli elementi della matrice a partire dal centro della matrice. Il Stack<T> costruttore viene usato di nuovo per creare una copia dello stack con l'ordine degli elementi invertiti, quindi i tre elementi Null si trovano alla fine.

Il Contains metodo viene usato 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.

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
 */
open System
open System.Collections.Generic

let numbers = Stack()
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 number in numbers do
    printfn $"{number}"

printfn $"\nPopping '{numbers.Pop()}'"
printfn $"Peek at next item to destack: {numbers.Peek()}"
numbers.Peek() |> ignore
printfn $"Popping '{numbers.Pop()}'"

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

printfn "\nContents of the first copy:"

for number in stack2 do
    printfn $"{number}"

// Create an array twice the size of the stack and copy the
// elements of the stack, starting at the middle of the
// array.
let array2 = numbers.Count * 2 |> Array.zeroCreate
numbers.CopyTo(array2, numbers.Count)

// Create a second stack, using the constructor that accepts an
// IEnumerable(Of T).
let stack3 = Stack array2

printfn "\nContents of the second copy, with duplicates and nulls:"

for number in stack3 do
    printfn $"{number}"

printfn
    $"""
stack2.Contains "four" = {stack2.Contains "four"}"""

printfn "\nstack2.Clear()"
stack2.Clear()
printfn $"\nstack2.Count = {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

La capacità di un Stack<T> oggetto è il numero di elementi che l'oggetto Stack<T> può contenere. Man mano che gli elementi vengono aggiunti a un Stack<T>oggetto , la capacità viene aumentata automaticamente in base alle esigenze tramite la riallocazione della matrice interna.

Se è possibile stimare le dimensioni della raccolta, specificando la capacità iniziale è possibile eliminare la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Stack<T>di elementi a .

La capacità può essere ridotta chiamando TrimExcess.

Gli elementi vengono copiati nell'oggetto Stack<T> nello stesso ordine in cui vengono letti dall'oggetto IEnumerator<T> della raccolta.

Questo costruttore è un'operazione O(n), dove n è il numero di elementi in collection.

Vedi anche

Si applica a

Stack<T>(Int32)

Source:
Stack.cs
Source:
Stack.cs
Source:
Stack.cs

Consente l'inizializzazione di una nuova istanza della classe Stack<T>, che è vuota e ha la capacità iniziale maggiore tra quella specificata e quella predefinita.

public:
 Stack(int capacity);
public Stack (int capacity);
new System.Collections.Generic.Stack<'T> : int -> System.Collections.Generic.Stack<'T>
Public Sub New (capacity As Integer)

Parametri

capacity
Int32

Numero iniziale degli elementi che Stack<T> può contenere.

Eccezioni

capacity è minore di zero.

Commenti

La capacità di un Stack<T> oggetto è il numero di elementi che l'oggetto Stack<T> può contenere. Man mano che gli elementi vengono aggiunti a un Stack<T>oggetto , la capacità viene aumentata automaticamente in base alle esigenze tramite la riallocazione della matrice interna.

Se è possibile stimare le dimensioni della raccolta, specificando la capacità iniziale è possibile eliminare la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Stack<T>di elementi a .

La capacità può essere ridotta chiamando TrimExcess.

Questo costruttore è un'operazione O(n), dove n è capacity.

Si applica a