IDictionary<TKey,TValue>.Item[TKey] Propriedade
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
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 para obter ou definir.
Valor de Propriedade
O elemento com a chave especificada.
Exceções
key é null.
A propriedade é recuperada e key não é encontrada.
A propriedade está definida e a IDictionary<TKey,TValue> é apenas leitura.
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 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 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: myCollection[key] (myCollection(key) em Visual Basic).
Também pode usar a propriedade Item[] para adicionar novos elementos definindo o valor de uma chave que não existe no dicionário; por exemplo, em C# ( em Visual Basic). No entanto, se a chave especificada já existir no dicionário, definir a Item[] propriedade sobrescreve o valor antigo. Em contraste, o Add método não modifica elementos existentes.
As implementações podem variar na forma como determinam a igualdade dos objetos; Por exemplo, a List<T> classe usa Comparer<T>.Default, enquanto a Dictionary<TKey,TValue> classe permite ao utilizador especificar a IComparer<T> implementação a usar para comparar chaves.
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.
As implementações podem variar quanto a permitir key ser null.