Condividi tramite


KeyValuePair<TKey,TValue> Struct

Definizione

Definisce una coppia chiave/valore che può essere impostata o recuperata.

generic <typename TKey, typename TValue>
public value class KeyValuePair
public struct KeyValuePair<TKey,TValue>
public readonly struct KeyValuePair<TKey,TValue>
[System.Serializable]
public struct KeyValuePair<TKey,TValue>
type KeyValuePair<'Key, 'Value> = struct
[<System.Serializable>]
type KeyValuePair<'Key, 'Value> = struct
Public Structure KeyValuePair(Of TKey, TValue)

Parametri di tipo

TKey

Tipo della chiave.

TValue

Tipo del valore.

Ereditarietà
KeyValuePair<TKey,TValue>
Attributi

Esempio

Nell'esempio di codice seguente viene illustrato come enumerare le chiavi e i valori in un dizionario usando la KeyValuePair<TKey,TValue> struttura .

Questo codice fa parte di un esempio più ampio fornito per la Dictionary<TKey,TValue> classe .

// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
    Console.WriteLine("Key = {0}, Value = {1}",
        kvp.Key, kvp.Value);
}
' When you use foreach to enumerate dictionary elements,
' the elements are retrieved as KeyValuePair objects.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In openWith
    Console.WriteLine("Key = {0}, Value = {1}", _
        kvp.Key, kvp.Value)
Next kvp

Commenti

La Dictionary<TKey,TValue>.Enumerator.Current proprietà restituisce un'istanza di questo tipo.

L'istruzione foreach del linguaggio C# (For Each in Visual Basic) restituisce un oggetto del tipo degli elementi nella raccolta. Poiché ogni elemento di una raccolta basata su IDictionary<TKey,TValue> è una coppia chiave/valore, il tipo di elemento non è il tipo della chiave o il tipo del valore. Il tipo di elemento è KeyValuePair<TKey,TValue>invece . Per esempio:

foreach( KeyValuePair<string, string> kvp in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
For Each kvp As KeyValuePair(Of String, String) In myDictionary
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value)
Next kvp

L'istruzione foreach è un wrapper intorno all'enumeratore, che consente solo la lettura, non la scrittura nella raccolta.

Costruttori

Nome Descrizione
KeyValuePair<TKey,TValue>(TKey, TValue)

Inizializza una nuova istanza della KeyValuePair<TKey,TValue> struttura con la chiave e il valore specificati.

Proprietà

Nome Descrizione
Key

Ottiene la chiave nella coppia chiave/valore.

Value

Ottiene il valore nella coppia chiave/valore.

Metodi

Nome Descrizione
Deconstruct(TKey, TValue)

Decostruisce l'oggetto corrente KeyValuePair<TKey,TValue>.

ToString()

Restituisce una rappresentazione di stringa di KeyValuePair<TKey,TValue>, utilizzando le rappresentazioni di stringa della chiave e del valore.

Si applica a

Vedi anche