Dictionary<TKey,TValue>.Item[TKey] Dictionary<TKey,TValue>.Item[TKey] Dictionary<TKey,TValue>.Item[TKey] Dictionary<TKey,TValue>.Item[TKey] Property

Definición

Obtiene o establece el valor asociado a la clave especificada.Gets or sets the value associated with the specified key.

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

Clave del valor que se va a obtener o establecer.The key of the value to get or set.

Valor de propiedad

TValue TValue TValue TValue

Valor asociado a la clave especificada.The value associated with the specified key. Si no se encuentra la clave especificada, en el caso de una operación Get se producirá una excepción KeyNotFoundException y en el caso de una operación de establecimiento se creará un nuevo elemento con la clave especificada.If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.

Implementaciones

Excepciones

Se ha recuperado la propiedad y key no existe en la colección.The property is retrieved and key does not exist in the collection.

Ejemplos

Nota

Algunos de los ejemplos de C# de este artículo se ejecutan en el ejecutor de código en línea y área de juegos de Try.NET.Some of the C# examples in this article run in the Try.NET inline code runner and playground. Si está presente, haga clic en el botón Ejecutar para ejecutar un ejemplo en una ventana interactiva.When present, select the Run button to run an example in an interactive window. Una vez que se ejecuta el código, puede modificar y ejecutar el código modificado si vuelve a hacer clic en Ejecutar.Once you execute the code, you can modify it and run the modified code by selecting Run again. El código modificado se ejecuta en la ventana interactiva o, si se produce un error en la compilación, en la ventana interactiva se muestran todos los mensajes de error del compilador de C#.The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

En el ejemplo de código siguiente Item[TKey] se usa la propiedad (el C#indizador en) para recuperar valores, lo que KeyNotFoundException muestra que se produce una excepción cuando una clave solicitada no está presente y que muestra que se puede reemplazar el valor asociado a una clave.The following code example uses the Item[TKey] property (the indexer in C#) to retrieve values, demonstrating that a KeyNotFoundException is thrown when a requested key is not present, and showing that the value associated with a key can be replaced.

En el ejemplo también se muestra cómo utilizar TryGetValue el método como una forma más eficaz de recuperar valores si un programa debe probar con frecuencia valores de clave que no están en el diccionario.The example also shows how to use the TryGetValue method as a more efficient way to retrieve values if a program often must try key values that are not in the dictionary.

Este ejemplo de código forma parte de un ejemplo más extenso proporcionado Dictionary<TKey,TValue> para la clase.This code example is part of a larger example provided for the Dictionary<TKey,TValue> class. openWithes el nombre del diccionario utilizado en este ejemplo.openWith is the name of the Dictionary used in this example.

// Create a new dictionary of strings, with string keys.
//
Dictionary<String^, String^>^ openWith =
    gcnew Dictionary<String^, String^>();

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith->Add("txt", "notepad.exe");
openWith->Add("bmp", "paint.exe");
openWith->Add("dib", "paint.exe");
openWith->Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
    openWith->Add("txt", "winword.exe");
}
catch (ArgumentException^)
{
    Console::WriteLine("An element with Key = \"txt\" already exists.");
}
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith = 
    new Dictionary<string, string>();

// Add some elements to the dictionary. There are no 
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is 
// already in the dictionary.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}
' Create a new dictionary of strings, with string keys.
'
Dim openWith As New Dictionary(Of String, String)

' Add some elements to the dictionary. There are no 
' duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")

' The Add method throws an exception if the new key is 
' already in the dictionary.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
// 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 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 indexer throws an exception if the requested key is
// not in the dictionary.
try
{
    Console::WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException^)
{
    Console::WriteLine("Key = \"tif\" is not found.");
}
// The indexer throws an exception if the requested key is
// not in the dictionary.
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 dictionary.
Try
    Console.WriteLine("For key = ""tif"", value = {0}.", _
        openWith("tif"))
Catch 
    Console.WriteLine("Key = ""tif"" is not found.")
End Try
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
String^ value = "";
if (openWith->TryGetValue("tif", 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 dictionary, 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 dictionary, 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

Comentarios

Esta propiedad proporciona la capacidad de obtener acceso a un elemento específico de la colección utilizando la C# sintaxis siguiente myCollection[key] :myCollection(key) (en Visual Basic).This property provides the ability to access a specific element in the collection by using the following C# syntax: myCollection[key] (myCollection(key) in Visual Basic).

También puede usar la Item[TKey] propiedad para agregar nuevos elementos estableciendo el valor de una clave que no existe Dictionary<TKey,TValue>en.You can also use the Item[TKey] property to add new elements by setting the value of a key that does not exist in the Dictionary<TKey,TValue>. Al establecer el valor de la propiedad, si la clave está en Dictionary<TKey,TValue>, el valor asociado a esa clave se reemplaza por el valor asignado.When you set the property value, if the key is in the Dictionary<TKey,TValue>, the value associated with that key is replaced by the assigned value. Si la clave no está en Dictionary<TKey,TValue>, se agregan la clave y el valor al diccionario.If the key is not in the Dictionary<TKey,TValue>, the key and value are added to the dictionary. En cambio, el Add método no modifica los elementos existentes.In contrast, the Add method does not modify existing elements.

Una clave no puede nullser, pero un valor puede ser, si el tipo TValue de valor es un tipo de referencia.A key cannot be null, but a value can be, if the value type TValue is a reference type.

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

Obtener o establecer el valor de esta propiedad se aproxima a una operación O (1).Getting or setting the value of this property approaches an O(1) operation.

Se aplica a

Consulte también: