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

Definição

Obtém ou define o elemento com a 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 elemento a ser obtida ou adicionada.

Valor da propriedade

TValue

O elemento com a chave especificada.

Exceções

key é null.

A propriedade é recuperada e key não foi encontrado.

A propriedade é definida e o IDictionary<TKey,TValue> é somente leitura.

Exemplos

O exemplo de código a seguir usa a Item[] propriedade (o indexador em C#) para recuperar valores, demonstrando que um KeyNotFoundException é gerado 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 maneira mais eficiente de recuperar valores se um programa geralmente precisar experimentar valores de chave que não estão no dicionário.

Esse código faz parte de um exemplo maior que pode ser compilado e executado. Consulte System.Collections.Generic.IDictionary<TKey,TValue>.

// 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 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 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", 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.
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

Comentários

Essa propriedade fornece a capacidade de acessar um elemento específico na coleção usando a seguinte sintaxe: myCollection[key] (myCollection(key) em Visual Basic).

Você também pode usar a Item[] propriedade para adicionar novos elementos definindo o valor de uma chave que não existe no dicionário; por exemplo, myCollection["myNonexistentKey"] = myValue em C# (myCollection("myNonexistentKey") = myValueem Visual Basic). No entanto, se a chave especificada já existir no dicionário, definir a Item[] propriedade substituirá o valor antigo. Por outro lado, o Add método não modifica os elementos existentes.

As implementações podem variar na forma como determinam a igualdade de objetos; por exemplo, a List<T> classe usa Comparer<T>.Default, enquanto a Dictionary<TKey,TValue> classe permite que o usuário especifique a IComparer<T> implementação a ser usada para comparar chaves.

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

As implementações podem variar se elas permitem key ser null.

Aplica-se a

Confira também