Dictionary<TKey,TValue>.IDictionary.Item[Object] Propriété

Définition

Obtient ou définit la valeur avec la clé spécifiée.

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

Paramètres

key
Object

Clé de la valeur à obtenir.

Valeur de propriété

Object

Valeur associée à la clé spécifiée, ou null si key ne figure pas dans le dictionnaire ou si le type de key ne peut pas être assigné au type de clé TKey de Dictionary<TKey,TValue>.

Implémente

Exceptions

key a la valeur null.

Une valeur est assignée et key a un type qui ne peut pas être assigné au type de clé TKey de Dictionary<TKey,TValue>.

  • ou - Une valeur est assignée et value a un type qui ne peut pas être assigné au type valeur TValue de Dictionary<TKey,TValue>.

Exemples

L’exemple de code suivant montre comment utiliser la IDictionary.Item[] propriété (l’indexeur en C#) de l’interface System.Collections.IDictionary avec un Dictionary<TKey,TValue>, et comment la propriété diffère de la Dictionary<TKey,TValue>.Item[] propriété.

L’exemple montre que, comme la Dictionary<TKey,TValue>.Item[] propriété, la Dictionary<TKey,TValue>.IDictionary.Item[] propriété peut modifier la valeur associée à une clé existante et être utilisée pour ajouter une nouvelle paire clé/valeur si la clé spécifiée n’est pas dans le dictionnaire. L’exemple montre également que contrairement à la Dictionary<TKey,TValue>.Item[] propriété, la Dictionary<TKey,TValue>.IDictionary.Item[] propriété ne lève pas d’exception si key elle n’est pas dans le dictionnaire, renvoyant une référence Null à la place. Enfin, l’exemple montre que l’obtention de la Dictionary<TKey,TValue>.IDictionary.Item[] propriété retourne une référence Null si key ce n’est pas le type de données correct et que la définition de la propriété lève une exception si key ce n’est pas le type de données correct.

L’exemple de code fait partie d’un exemple plus grand, y compris la sortie, fourni pour la IDictionary.Add méthode.

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");
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 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

Remarques

Cette propriété permet d’accéder à une valeur spécifique dans la collection à l’aide de la syntaxe C# suivante : myCollection[key] (myCollection(key)dans Visual Basic).

Vous pouvez également utiliser la Item[] propriété pour ajouter de nouveaux éléments en définissant la valeur d’une clé qui n’existe pas dans le dictionnaire , par exemple. myCollection["myNonexistentKey"] = myValue Toutefois, si la clé spécifiée existe déjà dans le dictionnaire, la définition de la propriété remplace l’ancienne Item[] valeur. En revanche, la Add méthode ne modifie pas les éléments existants.

Le langage C# utilise ce mot clé pour définir les indexeurs au lieu d’implémenter la IDictionary.Item[] propriété. Visual Basic implémente IDictionary.Item[] comme propriété par défaut, ce qui fournit les mêmes fonctionnalités d'indexation.

L’obtention ou la définition de la valeur de cette propriété approche une opération O(1).

S’applique à

Voir aussi