Compartilhar via


KeyValuePair<TKey,TValue> Estrutura

Definição

Define um par chave/valor que pode ser definido ou recuperado.

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)

Parâmetros de tipo

TKey

O tipo da chave.

TValue

O tipo do valor.

Herança
KeyValuePair<TKey,TValue>
Atributos

Exemplos

O exemplo de código a seguir mostra como enumerar as chaves e os valores em um dicionário usando a KeyValuePair<TKey,TValue> estrutura.

Esse código faz parte de um exemplo maior fornecido para a 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

Comentários

A Dictionary<TKey,TValue>.Enumerator.Current propriedade retorna uma instância desse tipo.

A foreach instrução da linguagem C# (For Each no Visual Basic) retorna um objeto do tipo dos elementos na coleção. Como cada elemento de uma coleção com IDictionary<TKey,TValue> base é um par chave/valor, o tipo de elemento não é o tipo da chave ou o tipo do valor. Em vez disso, o tipo de elemento é KeyValuePair<TKey,TValue>. Por exemplo:

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

A foreach instrução é um wrapper em torno do enumerador, que permite apenas a leitura de, não gravando para, a coleção.

Construtores

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

Inicializa uma nova instância da KeyValuePair<TKey,TValue> estrutura com a chave e o valor especificados.

Propriedades

Nome Description
Key

Obtém a chave no par chave/valor.

Value

Obtém o valor no par chave/valor.

Métodos

Nome Description
Deconstruct(TKey, TValue)

Desconstrui o atual KeyValuePair<TKey,TValue>.

ToString()

Retorna uma representação de cadeia de caracteres do KeyValuePair<TKey,TValue>, usando as representações de cadeia de caracteres da chave e do valor.

Aplica-se a

Confira também