SortedList<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 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 cujo valor deve ser obtido ou definido.
Valor de Propriedade
O valor associado à chave especificada. Se a chave especificada não for encontrada, uma operação get lança a KeyNotFoundException e uma operação set cria um novo elemento usando 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 na lista ordenada.
Este exemplo de código faz parte de um exemplo maior fornecido para a SortedList<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 Item property is another name for the indexer, so you
// can omit its name when accessing elements.
printfn $"""For key = "rtf", value = {openWith["rtf"]}."""
// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] <- "winword.exe"
printfn $"""For key = "rtf", value = {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 indexer throws an exception if the requested key is
// not in the list.
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 list.
Try
Console.WriteLine("For key = ""tif"", value = {0}.", _
openWith("tif"))
Catch
Console.WriteLine("Key = ""tif"" is not found.")
End Try
// The indexer throws an exception if the requested key is
// not in the list.
try
printfn $"""For key = "tif", value = {openWith["tif"]}."""
with
| :? KeyNotFoundException ->
printfn "Key = \"tif\" is not found."
// When a program often has to try keys that turn out not to
// be in the list, 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 list, 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
// When a program often has to try keys that turn out not to
// be in the list, TryGetValue can be a more efficient
// way to retrieve values.
match openWith.TryGetValue("tif") with
| true, value ->
printfn "For key = \"tif\", value = {value}."
| false, _ ->
printfn "Key = \"tif\" is not found."
Observações
Esta propriedade permite aceder a um elemento específico da coleção utilizando a seguinte sintaxe: myCollection[key].
Uma chave não pode ser null, mas um valor pode ser, se o tipo de valores na lista, TValue, for um tipo de referência.
Se a chave não for encontrada quando um valor está a ser recuperado, KeyNotFoundException é lançada. Se a chave não for encontrada quando um valor está a ser definido, a chave e o valor são somados.
Também pode usar a Item[] propriedade para adicionar novos elementos definindo o valor de uma chave que não existe no SortedList<TKey,TValue>; por exemplo, myCollection["myNonexistentKey"] = myValue. No entanto, se a chave especificada já existir no SortedList<TKey,TValue>, definindo a Item[] propriedade sobrescreve o valor antigo. Em contraste, o Add método não modifica elementos existentes.
A linguagem C# usa a this palavra-chave para definir os indexadores em vez de implementar a propriedade Item[] . Visual Basic implementa Item[] como propriedade predefinida, que fornece a mesma funcionalidade de indexação.
Recuperar o valor desta propriedade é uma operação O(log n), onde n é Count. Definir a propriedade é uma operação O(log n) se a chave já estiver no SortedList<TKey,TValue>. Se a chave não estiver na lista, definir a propriedade é uma operação O(n) para dados não ordenados, ou O(log n) se o novo elemento for adicionado no final da lista. Se a inserção causar um redimensionamento, a operação é O(n).