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

Definición

Obtiene o establece el elemento con la clave especificada.Gets or sets the element with the specified key.

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; }
 Property Item(key As Object) As Object Implements IDictionary.Item

Parámetros

key
Object Object Object

La clave del elemento que se obtiene o establece.The key of the element to get or set.

Valor de propiedad

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 SortedList<TKey,TValue>.The element with the specified key, or null if key is not in the dictionary or key is of a type that is not assignable to the key type TKey of the SortedList<TKey,TValue>.

Implementaciones

Excepciones

Se está asignando un valor, pero key es de un tipo no asignable al tipo de clave TKey de SortedList<TKey,TValue>.A value is being assigned, and key is of a type that is not assignable to the key type TKey of the SortedList<TKey,TValue>.

o bien-or- Se está asignando un valor, pero value es de un tipo no asignable al tipo de valor TValue de SortedList<TKey,TValue>.A value is being assigned, and value is of a type that is not assignable to the value type TValue of the SortedList<TKey,TValue>.

Ejemplos

En el ejemplo de código siguiente se muestra cómo IDictionary.Item[Object] utilizar la propiedad (el indizador en C#) System.Collections.IDictionary de SortedList<TKey,TValue>la interfaz con, y las formas en que la propiedad SortedList<TKey,TValue>.Item[TKey] difiere de la propiedad.The following code example shows how to use the IDictionary.Item[Object] property (the indexer in C#) of the System.Collections.IDictionary interface with a SortedList<TKey,TValue>, and ways the property differs from the SortedList<TKey,TValue>.Item[TKey] property.

En el ejemplo se muestra que, SortedList<TKey,TValue>.Item[TKey] al igual que SortedList<TKey,TValue>.IDictionary.Item[Object] la propiedad, la 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 la lista ordenada.The example shows that, like the SortedList<TKey,TValue>.Item[TKey] property, the SortedList<TKey,TValue>.IDictionary.Item[Object] property can change the value associated with an existing key and can be used to add a new key/value pair if the specified key is not in the sorted list. En el ejemplo también se muestra que, SortedList<TKey,TValue>.Item[TKey] a diferencia de SortedList<TKey,TValue>.IDictionary.Item[Object] la propiedad, la propiedad no inicia key una excepción si no está en la lista ordenada y devuelve en su lugar una referencia nula.The example also shows that unlike the SortedList<TKey,TValue>.Item[TKey] property, the SortedList<TKey,TValue>.IDictionary.Item[Object] property does not throw an exception if key is not in the sorted list, returning a null reference instead. Por último, en el ejemplo se muestra SortedList<TKey,TValue>.IDictionary.Item[Object] que la obtención de la propiedad key devuelve una referencia nula si no es el tipo de datos correcto y el establecimiento de la key propiedad produce una excepción si no es el tipo de datos correcto.Finally, the example demonstrates that getting the SortedList<TKey,TValue>.IDictionary.Item[Object] property returns a null reference if key is not the correct data type, and that setting the property throws an exception if key is not the correct data type.

El ejemplo de código forma parte de un ejemplo más grande, incluido el resultado, IDictionary.Add proporcionado para el método.The code example is part of a larger example, including output, provided for the IDictionary.Add method.

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

Comentarios

Esta propiedad devuelve null si key es de un tipo que no se puede asignar al tipo TKey de clave de SortedList<TKey,TValue>.This property returns null if key is of a type that is not assignable to the key type TKey of the SortedList<TKey,TValue>.

Esta propiedad permite obtener acceso a un elemento específico de la colección utilizando la sintaxis siguiente: myCollection[key].This property provides the ability to access a specific element in the collection by using the following syntax: myCollection[key].

También puede usar la Item[Object] propiedad para agregar nuevos elementos estableciendo el valor de una clave que no existe en el diccionario; por ejemplo,. myCollection["myNonexistentKey"] = myValueYou can also use the Item[Object] property to add new elements by setting the value of a key that does not exist in the dictionary; for example, myCollection["myNonexistentKey"] = myValue. Sin embargo, si la clave especificada ya existe en el diccionario, al Item[Object] establecer la propiedad se sobrescribe el valor anterior.However, if the specified key already exists in the dictionary, setting the Item[Object] property overwrites the old value. En cambio, el Add método no modifica los elementos existentes.In contrast, the Add method does not modify existing elements.

El C# lenguaje utiliza la palabra clave this para definir los indizadores en lugar de implementar IDictionary.Item[Object] la propiedad.The C# language uses the this keyword to define the indexers instead of implementing the IDictionary.Item[Object] property. Visual Basic implementa IDictionary.Item[Object] como propiedad predeterminada, lo que proporciona la misma funcionalidad de indización.Visual Basic implements IDictionary.Item[Object] as a default property, which provides the same indexing functionality.

La recuperación del valor de esta propiedad es una operación O ( nlog), donde n es Count.Retrieving the value of this property is an O(log n) operation, where n is Count. Establecer la propiedad es una operación O ( nlog) si la clave ya está SortedList<TKey,TValue>en.Setting the property is an O(log n) operation if the key is already in the SortedList<TKey,TValue>. Si la clave no está en la lista, el establecimiento de la propiedad es unanoperación O () para los datos sin ordenar o o ( nlog) si el nuevo elemento se agrega al final de la lista.If the key is not in the list, setting the property is an O(n) operation for unsorted data, or O(log n) if the new element is added at the end of the list. Si la inserción provoca un redimensionamiento, la operación esnO ().If insertion causes a resize, the operation is O(n).

Se aplica a

Consulte también: