Dictionary<TKey,TValue>.IDictionary.Item[Object] Propiedad
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Obtiene o establece el valor 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 valor que se va a obtener.
Valor de propiedad
Valor asociado a la clave especificada, o null si key no está en el diccionario o key es de un tipo que no se puede asignar al tipo TKey de clave de Dictionary<TKey,TValue>.
Implementaciones
Excepciones
key es null.
Se asigna un valor y key es de un tipo que no se puede asignar al tipo TKey de clave de Dictionary<TKey,TValue>.
O bien
Se asigna un valor y es de un tipo que no se puede asignar al tipo TValue de valor de Dictionary<TKey,TValue>.
Ejemplos
En el ejemplo de código siguiente se muestra cómo usar la IDictionary.Item[] propiedad (el indizador en C#) de la System.Collections.IDictionary interfaz con y Dictionary<TKey,TValue>las formas en que la propiedad difiere de la Dictionary<TKey,TValue>.Item[] propiedad .
En el ejemplo se muestra que, al igual que la Dictionary<TKey,TValue>.Item[] propiedad , la Dictionary<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 Dictionary<TKey,TValue>.Item[] propiedad , la Dictionary<TKey,TValue>.IDictionary.Item[] propiedad no produce una excepción si key no está en el diccionario, devolviendo en su lugar una referencia nula. Por último, el ejemplo muestra que la obtención de la Dictionary<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.
using System;
using System.Collections;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new dictionary of strings, with string keys,
// and access it using the IDictionary interface.
//
IDictionary openWith = new Dictionary<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 = {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 = {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 = {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.");
}
// 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 = {openWith["tif"]}.""");
}
}
open System
open System.Collections
open System.Collections.Generic
// Create a new dictionary of strings, with string keys,
// and access it using the IDictionary interface.
let openWith: IDictionary = Dictionary<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.
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 returns null if the key is of the wrong data
// type.
printfn "The indexer returns null if the key is of the wrong type:"
printfn $"""For key = 2, value = {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."
with :? ArgumentException ->
printfn "A key of the wrong type was specified when assigning to the indexer."
// 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.
printfn $"""For key = "tif", value = {openWith.["tif"]}."""
Imports System.Collections
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new dictionary of strings, with string keys,
' and access it using the IDictionary interface.
'
Dim openWith As IDictionary = _
New Dictionary(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 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"))
End Sub
End Class
Comentarios
Esta propiedad proporciona la capacidad de acceder a un valor 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 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 una propiedad predeterminada, que proporciona la misma funcionalidad de indexación.
Obtener o establecer el valor de esta propiedad se aproxima a una operación O(1).