Condividi tramite


Dictionary<TKey,TValue>.IDictionary.GetEnumerator Metodo

Definizione

Restituisce un oggetto IDictionaryEnumerator per l'oggetto IDictionary.

 virtual System::Collections::IDictionaryEnumerator ^ System.Collections.IDictionary.GetEnumerator() = System::Collections::IDictionary::GetEnumerator;
System.Collections.IDictionaryEnumerator IDictionary.GetEnumerator();
abstract member System.Collections.IDictionary.GetEnumerator : unit -> System.Collections.IDictionaryEnumerator
override this.System.Collections.IDictionary.GetEnumerator : unit -> System.Collections.IDictionaryEnumerator
Function GetEnumerator () As IDictionaryEnumerator Implements IDictionary.GetEnumerator

Restituisce

Oggetto IDictionaryEnumerator per l'oggetto IDictionary.

Implementazioni

Esempio

Nell'esempio di codice seguente viene illustrato come enumerare le coppie chiave/valore nel dizionario usando l'istruzione foreach (For Each in Visual Basic), che nasconde l'uso dell'enumeratore. In particolare, si noti che l'enumeratore per l'interfaccia System.Collections.IDictionary restituisce DictionaryEntry oggetti anziché KeyValuePair<TKey,TValue> oggetti.

using System;
using System.Collections;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys,
        // and access it using the IDictionary interface.
        //
        IDictionary openWith = new Dictionary<string, string>();

        // Add some elements to the dictionary. There are no
        // duplicate keys, but some of the values are duplicates.
        // IDictionary.Add throws an exception if incorrect types
        // are supplied for key or value.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // When you use foreach to enumerate dictionary elements
        // with the IDictionary interface, the elements are retrieved
        // as DictionaryEntry objects instead of KeyValuePair objects.
        foreach( DictionaryEntry de in openWith )
        {
            Console.WriteLine($"Key = {de.Key}, Value = {de.Value}");
        }
    }
}
open System
open System.Collections
open System.Collections.Generic

// Create a new dictionary of strings, with string keys,
// and access it using the IDictionary interface.
let openWith: IDictionary = Dictionary<string, string>()

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
// IDictionary.Add throws an exception if incorrect types
// are supplied for key or value.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")

// When you use foreach to enumerate dictionary elements
// with the IDictionary interface, the elements are retrieved
// as DictionaryEntry objects instead of KeyValuePair objects.
printfn ""

for de in openWith do
    let de = de :?> DictionaryEntry
    printfn $"For key = {de.Key}, value = {de.Value}"
Imports System.Collections
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new dictionary of strings, with string keys,
        ' and access it using the IDictionary interface.
        '
        Dim openWith As IDictionary = _
            New Dictionary(Of String, String)
        
        ' Add some elements to the dictionary. There are no 
        ' duplicate keys, but some of the values are duplicates.
        ' IDictionary.Add throws an exception if incorrect types
        ' are supplied for key or value.
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")

        ' When you use foreach to enumerate dictionary elements
        ' with the IDictionary interface, the elements are retrieved
        ' as DictionaryEntry objects instead of KeyValuePair objects.
        Console.WriteLine()
        For Each de As DictionaryEntry In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                de.Key, de.Value)
        Next 

    End Sub

End Class

Commenti

Ai fini dell'enumerazione, ogni elemento è una DictionaryEntry struttura.

L'istruzione foreach del linguaggio C# (For Each in Visual Basic) nasconde la complessità degli enumeratori. Pertanto, è consigliabile usare foreach anziché modificare direttamente l'enumeratore.

Gli enumeratori possono essere usati per leggere i dati nella raccolta, ma non possono essere usati per modificare la raccolta sottostante.

Inizialmente, l'enumeratore viene posizionato prima del primo elemento della raccolta. Il Reset metodo riporta anche l'enumeratore in questa posizione. In questa posizione, Entry non è definito. Pertanto, è necessario chiamare il MoveNext metodo per far avanzare l'enumeratore al primo elemento della raccolta prima di leggere il valore di Entry.

La Entry proprietà restituisce lo stesso elemento finché non viene chiamato il MoveNext metodo o Reset . MoveNext imposta Entry sull'elemento successivo.

Se MoveNext passa la fine della raccolta, l'enumeratore viene posizionato dopo l'ultimo elemento della raccolta e MoveNext restituisce false. Quando l'enumeratore si trova in questa posizione, le chiamate successive per MoveNext restituire falseanche . Se l'ultima chiamata a MoveNext restituisce false, Entry non è definita. Per impostare Entry di nuovo sul primo elemento della raccolta, è possibile chiamare Reset seguito da MoveNext.

Un enumeratore rimane valido finché la raccolta rimane invariata. Se vengono apportate modifiche alla raccolta, ad esempio l'aggiunta di elementi o la modifica della capacità, l'enumeratore viene invalidato in modo irreversibile e la chiamata successiva a MoveNext o IEnumerator.Reset genera un'eccezione InvalidOperationException.

Solo .NET Core 3.0+: gli unici metodi di modifica che non invalidano gli enumeratori sono Remove e Clear.

L'enumeratore non ha accesso esclusivo alla raccolta; pertanto, l'enumerazione tramite una raccolta non è intrinsecamente una procedura thread-safe. Per garantire la thread safety durante l'enumerazione, è possibile bloccare la raccolta durante l'intera enumerazione. Per consentire l'accesso alla raccolta da parte di più thread per la lettura e la scrittura, è necessario implementare la propria sincronizzazione.

Le implementazioni predefinite delle raccolte nello System.Collections.Generic spazio dei nomi non vengono sincronizzate.

Questo metodo è un'operazione O(1).

Si applica a

Vedi anche