SortedDictionary<TKey,TValue>.Item[TKey] Propriedade

Definição

Obtém ou define o valor associado à chave especificada.

public:
 property TValue default[TKey] { TValue get(TKey key); void set(TKey key, TValue value); };
public TValue this[TKey key] { get; set; }
member this.Item('Key) : 'Value with get, set
Default Public Property Item(key As TKey) As TValue

Parâmetros

key
TKey

A chave do valor a obter ou definir.

Valor de Propriedade

TValue

O valor associado à chave especificada. Se a chave especificada não for encontrada, uma operação get lança um KeyNotFoundException, e uma operação de conjunto cria um novo elemento com a chave especificada.

Implementações

Exceções

key é null.

A propriedade é recuperada e key não existe na coleção.

Exemplos

O exemplo de código seguinte usa a Item[] propriedade (o indexador em C#) para recuperar valores, demonstrando que a KeyNotFoundException é lançado quando uma chave solicitada não está presente, e mostrando que o valor associado a uma chave pode ser substituído.

O exemplo também mostra como usar o TryGetValue método como uma forma mais eficiente de recuperar valores se um programa frequentemente tiver de tentar valores-chave que não estão no dicionário.

Este exemplo de código faz parte de um exemplo maior fornecido para a SortedDictionary<TKey,TValue> classe.

// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
' The Item property is the default property, so you 
' can omit its name when accessing elements. 
Console.WriteLine("For key = ""rtf"", value = {0}.", _
    openWith("rtf"))

' The default Item property can be used to change the value
' associated with a key.
openWith("rtf") = "winword.exe"
Console.WriteLine("For key = ""rtf"", value = {0}.", _
    openWith("rtf"))

' If a key does not exist, setting the default Item property
' for that key adds a new key/value pair.
openWith("doc") = "winword.exe"
// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
    Console.WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
' The default Item property throws an exception if the requested
' key is not in the dictionary.
Try
    Console.WriteLine("For key = ""tif"", value = {0}.", _
        openWith("tif"))
Catch 
    Console.WriteLine("Key = ""tif"" is not found.")
End Try
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
' When a program often has to try keys that turn out not to
' be in the dictionary, TryGetValue can be a more efficient 
' way to retrieve values.
Dim value As String = ""
If openWith.TryGetValue("tif", value) Then
    Console.WriteLine("For key = ""tif"", value = {0}.", value)
Else
    Console.WriteLine("Key = ""tif"" is not found.")
End If

Observações

Esta propriedade permite aceder a um elemento específico da coleção utilizando a seguinte sintaxe C#: myCollection[key] (myCollection(key) em Visual Basic).

Também pode usar a Item[] propriedade para adicionar novos elementos definindo o valor de uma chave que não existe no SortedDictionary<TKey,TValue>; por exemplo, myCollection["myNonexistentKey"] = myValue. No entanto, se a chave especificada já existir no SortedDictionary<TKey,TValue>, definindo a Item[] propriedade sobrescreve o valor antigo. Em contraste, o Add método não modifica elementos existentes.

Uma chave não pode ser null, mas um valor pode ser, se o tipo TValue de valor for um tipo de referência.

A linguagem C# usa esta palavra-chave para definir os indexadores em vez de implementar a Item[] propriedade. Visual Basic implementa Item[] como propriedade predefinida, que fornece a mesma funcionalidade de indexação.

Obter o valor desta propriedade é uma operação O(log n); definir a propriedade também é uma operação O(log n).

Aplica-se a

Ver também