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

Definição

Obtém ou define o elemento com a chave especificada.

property System::Object ^ System::Collections::IDictionary::Item[System::Object ^] { System::Object ^ get(System::Object ^ key); void set(System::Object ^ key, System::Object ^ value); };
object System.Collections.IDictionary.Item[object key] { get; set; }
object? System.Collections.IDictionary.Item[object key] { get; set; }
member this.System.Collections.IDictionary.Item(obj) : obj with get, set
 Property Item(key As Object) As Object Implements IDictionary.Item

Parâmetros

key
Object

A chave do elemento a ser obtida ou adicionada.

Valor da propriedade

Object

O elemento com a chave especificada ou null se key não estiver no dicionário ou key for de um tipo que não é atribuível ao tipo TKey de chave do SortedList<TKey,TValue>.

Implementações

Exceções

key é null.

Um valor está sendo atribuído e key é de um tipo que não é atribuível ao tipo de chave TKey do SortedList<TKey,TValue>.

- ou - Um valor está sendo atribuído e value é de um tipo que não é atribuível ao tipo de valor TValue do SortedList<TKey,TValue>.

Exemplos

O exemplo de código a seguir mostra como usar a IDictionary.Item[] propriedade (o indexador em C#) da System.Collections.IDictionary interface com um SortedList<TKey,TValue>e como a propriedade difere da SortedList<TKey,TValue>.Item[] propriedade.

O exemplo mostra que, assim como a SortedList<TKey,TValue>.Item[] propriedade, a SortedList<TKey,TValue>.IDictionary.Item[] propriedade pode alterar o valor associado a uma chave existente e pode ser usada para adicionar um novo par chave/valor se a chave especificada não estiver na lista classificada. O exemplo também mostra que, ao contrário da SortedList<TKey,TValue>.Item[] propriedade, a SortedList<TKey,TValue>.IDictionary.Item[] propriedade não gerará uma exceção se key não estiver na lista classificada, retornando uma referência nula. Por fim, o exemplo demonstra que obter a SortedList<TKey,TValue>.IDictionary.Item[] propriedade retorna uma referência nula se key não for o tipo de dados correto e que a configuração da propriedade gerará uma exceção se key não for o tipo de dados correto.

O exemplo de código faz parte de um exemplo maior, inclusive saída, fornecido para o método IDictionary.Add.

using System;
using System.Collections;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new sorted list of strings, with string keys,
        // and access it using the IDictionary interface.
        //
        IDictionary openWith = new SortedList<string, string>();

        // Add some elements to the sorted list. There are no
        // duplicate keys, but some of the values are duplicates.
        // IDictionary.Add throws an exception if incorrect types
        // are supplied for key or value.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");
Imports System.Collections
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new sorted list of strings, with string keys,
        ' and access it using the IDictionary interface.
        '
        Dim openWith As IDictionary = _
            New sortedList(Of String, String)
        
        ' Add some elements to the sorted list. There are no 
        ' duplicate keys, but some of the values are duplicates.
        ' IDictionary.Add throws an exception if incorrect types
        ' are supplied for key or value.
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.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 indexer returns null if the key is of the wrong data
// type.
Console.WriteLine("The indexer returns null"
    + " if the key is of the wrong type:");
Console.WriteLine("For key = 2, value = {0}.",
    openWith[2]);

// The indexer throws an exception when setting a value
// if the key is of the wrong data type.
try
{
    openWith[2] = "This does not get added.";
}
catch (ArgumentException)
{
    Console.WriteLine("A key of the wrong type was specified"
        + " when assigning to the indexer.");
}
' 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 default Item property returns Nothing if the key
' is of the wrong data type.
Console.WriteLine("The default Item property returns Nothing" _
    & " if the key is of the wrong type:")
Console.WriteLine("For key = 2, value = {0}.", _
    openWith(2))

' The default Item property throws an exception when setting
' a value if the key is of the wrong data type.
Try
    openWith(2) = "This does not get added."
Catch 
    Console.WriteLine("A key of the wrong type was specified" _
        & " when setting the default Item property.")
End Try
// Unlike the default Item property on the SorteList class
// itself, IDictionary.Item does not throw an exception
// if the requested key is not in the sorted list.
Console.WriteLine("For key = \"tif\", value = {0}.",
    openWith["tif"]);
' Unlike the default Item property on the SortedList class
' itself, IDictionary.Item does not throw an exception
' if the requested key is not in the sorted list.
Console.WriteLine("For key = ""tif"", value = {0}.", _
    openWith("tif"))
    }
}

    End Sub

End Class

Comentários

Essa propriedade retorna null se key for de um tipo que não é atribuível ao tipo TKey de chave do SortedList<TKey,TValue>.

Esta propriedade fornece a capacidade de acessar um elemento específico na coleção usando a seguinte sintaxe: myCollection[key].

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. 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.

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

Recuperar o valor dessa propriedade é uma operação O(log n), onde n está Count. Definir a propriedade será uma operação O(log n) se a chave já estiver no SortedList<TKey,TValue>. Se a chave não estiver na lista, a configuração da propriedade será uma operação O(n) para dados não classificados ou O(log n) se o novo elemento for adicionado no final da lista. Se a inserção causar um redimensionamento, a operação será O(n).

Aplica-se a

Confira também