SortedDictionary<TKey,TValue>.IDictionary.Item[Object] Propiedad

Definición

Obtiene o establece el elemento con la clave 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

Clave del elemento que se va a obtener.

Valor de propiedad

Object

Elemento con la clave especificada, o null si key no está en el diccionario o si key es de un tipo no asignable al tipo de clave TKey de SortedDictionary<TKey,TValue>.

Implementaciones

Excepciones

key es null.

Se está asignando un valor, pero key es de un tipo no asignable al tipo de clave TKey de SortedDictionary<TKey,TValue>.

O bien Se está asignando un valor, pero value es de un tipo no asignable al tipo de valor TValue de SortedDictionary<TKey,TValue>.

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar la IDictionary.Item[] propiedad (el indexador en C#) de la System.Collections.IDictionary interfaz con y SortedDictionary<TKey,TValue>las formas en que la propiedad difiere de la SortedDictionary<TKey,TValue>.Item[] propiedad .

En el ejemplo se muestra que, al igual que la SortedDictionary<TKey,TValue>.Item[] propiedad , la SortedDictionary<TKey,TValue>.IDictionary.Item[] propiedad puede cambiar el valor asociado a una clave existente y se puede usar para agregar un nuevo par clave-valor si la clave especificada no está en el diccionario. En el ejemplo también se muestra que, a diferencia de la SortedDictionary<TKey,TValue>.Item[] propiedad , la SortedDictionary<TKey,TValue>.IDictionary.Item[] propiedad no produce una excepción si key no está en el diccionario y devuelve una referencia nula en su lugar. Por último, en el ejemplo se muestra que la obtención de la SortedDictionary<TKey,TValue>.IDictionary.Item[] propiedad devuelve una referencia nula si key no es el tipo de datos correcto y que al establecer la propiedad se produce una excepción si key no es el tipo de datos correcto.

El ejemplo de código forma parte de un ejemplo más grande, incluido el resultado, proporcionado para el IDictionary.Add método .

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

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

        // Add some elements to the dictionary. 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 dictionary of strings, with string keys,
        ' and access it using the IDictionary interface.
        '
        Dim openWith As IDictionary = _
            New SortedDictionary(Of String, String)
        
        ' Add some elements to the dictionary. 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 Dictionary class
// itself, IDictionary.Item does not throw an exception
// if the requested key is not in the dictionary.
Console.WriteLine("For key = \"tif\", value = {0}.",
    openWith["tif"]);
' Unlike the default Item property on the Dictionary class
' itself, IDictionary.Item does not throw an exception
' if the requested key is not in the dictionary.
Console.WriteLine("For key = ""tif"", value = {0}.", _
    openWith("tif"))
    }
}

    End Sub

End Class

Comentarios

Esta propiedad proporciona la capacidad de acceder a un elemento específico de la colección mediante la siguiente sintaxis de C#: ( myCollection[key]``myCollection(key) en Visual Basic).

También puede usar la Item[] propiedad para agregar nuevos elementos estableciendo el valor de una clave que no existe en el diccionario; por ejemplo, myCollection["myNonexistentKey"] = myValue. Sin embargo, si la clave especificada ya existe en el diccionario, al establecer la Item[] propiedad se sobrescribe el valor anterior. En cambio, el IDictionary.Add método no modifica los elementos existentes.

El lenguaje C# usa la palabra clave this para definir los indexadores en lugar de implementar la IDictionary.Item[] propiedad . Visual Basic implementa IDictionary.Item[] como propiedad predeterminada, lo que proporciona la misma funcionalidad de indización.

Obtener el valor de esta propiedad es una operación de O(log n); establecer la propiedad también es una operación O(log n).

Se aplica a

Consulte también