Assembly : mscorlib (dans mscorlib.dll)
SyntaxePublic Interface IDictionary(Of TKey, TValue) Inherits ICollection(Of KeyValuePair(Of TKey, TValue)), IEnumerable(Of KeyValuePair(Of TKey, TValue)), _ IEnumerable
Dim instance As IDictionary(Of TKey, TValue)
public interface IDictionary<TKey,TValue> : ICollection<KeyValuePair<TKey,TValue>>, IEnumerable<KeyValuePair<TKey,TValue>>,
IEnumerable
generic<typename TKey, typename TValue> public interface class IDictionary : ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
J# prend en charge l'utilisation de types et de méthodes génériques mais pas la déclaration de nouveaux types et de méthodes génériques.
JScript ne prend pas en charge les types et les méthodes génériques.
Paramètres de type
- TKey
Type des clés du dictionnaire.
- TValue
Type des valeurs du dictionnaire.
NotesL'interface IDictionary est l'interface de base pour les collections génériques de paires clé/valeur.
Chaque élément est une paire clé/valeur stockée dans un objet KeyValuePair.
Chaque paire doit avoir une clé unique. Les implémentations peuvent varier selon que key a la valeur référence Null (Nothing en Visual Basic) ou non. La valeur peut être référence Null (Nothing en Visual Basic) et il n'est pas nécessaire qu'elle soit unique. L'interface IDictionary permet d'énumérer les clés et valeurs, mais n'impose pas un ordre de tri particulier.
L'instruction foreach du langage C# (For Each en Visual Basic, for each en C++) requiert le type de chaque élément de la collection. Étant donné que chaque élément de IDictionary est une paire clé/valeur, le type d'élément n'est pas le type de la clé, ni le type de la valeur. Le type d'élément est plutôt KeyValuePair. Exemple :
foreach (KeyValuePair<int, string> kvp in myDictionary) {...}
for each (KeyValuePair<int, String^> kvp in myDictionary) {...}
For Each kvp As KeyValuePair(Of Integer, String) In myDictionary ... Next kvp
L'instruction foreach est un wrapper autour de l'énumérateur, qui permet la lecture à partir de la collection, mais non l'écriture dans celle-ci.
Remarques à l'attention des implémenteurs La classe d'implémentation doit disposer d'un moyen de comparer des clés.
ExempleL'exemple de code suivant crée un Dictionary de chaînes vide, avec des clés entières, et y accède par le biais de l'interface IDictionary.
L'exemple de code utilise la méthode Add pour ajouter des éléments. L'exemple montre que la méthode Add lève ArgumentException lors de la tentative d'ajout d'une clé dupliquée.
L'exemple utilise la propriété Item (l'indexeur en C#) pour récupérer des valeurs, démontrant qu'une KeyNotFoundException est levée lorsqu'une clé demandée n'est pas présente et indiquant que la valeur associée à une clé peut être remplacée.
L'exemple montre comment utiliser la méthode TryGetValue comme un moyen plus efficace de récupérer des valeurs si un programme doit souvent essayer des valeurs de clés qui ne sont pas dans le dictionnaire, et comment utiliser la méthode ContainsKey pour tester si une clé existe avant d'appeler la méthode Add.
Pour finir, l'exemple montre comment énumérer les clés et valeurs dans le dictionnaire et comment énumérer uniquement les valeurs à l'aide de la propriété Values.
Imports System Imports System.Collections.Generic Public Class Example Public Shared Sub Main() ' Create a new dictionary of strings, with string keys, ' and access it through the IDictionary generic interface. Dim openWith As IDictionary(Of String, String) = _ 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 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 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. 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 ' ContainsKey can be used to test keys before inserting ' them. If Not openWith.ContainsKey("ht") Then openWith.Add("ht", "hypertrm.exe") Console.WriteLine("Value added for key = ""ht"": {0}", _ openWith("ht")) End If ' When you use foreach to enumerate dictionary elements, ' the elements are retrieved as KeyValuePair objects. Console.WriteLine() For Each kvp As KeyValuePair(Of String, String) In openWith Console.WriteLine("Key = {0}, Value = {1}", _ kvp.Key, kvp.Value) Next kvp ' To get the values alone, use the Values property. Dim icoll As ICollection(Of String) = openWith.Values ' The elements of the ValueCollection are strongly typed ' with the type that was specified for dictionary values. Console.WriteLine() For Each s As String In icoll Console.WriteLine("Value = {0}", s) Next s ' To get the keys alone, use the Keys property. icoll = openWith.Keys ' The elements of the ValueCollection are strongly typed ' with the type that was specified for dictionary values. Console.WriteLine() For Each s As String In icoll Console.WriteLine("Key = {0}", s) Next s ' Use the Remove method to remove a key/value pair. Console.WriteLine(vbLf + "Remove(""doc"")") openWith.Remove("doc") If Not openWith.ContainsKey("doc") Then Console.WriteLine("Key ""doc"" is not found.") End If End Sub End Class ' This code example produces the following output: ' 'An element with Key = "txt" already exists. 'For key = "rtf", value = wordpad.exe. 'For key = "rtf", value = winword.exe. 'Key = "tif" is not found. 'Key = "tif" is not found. 'Value added for key = "ht": hypertrm.exe ' 'Key = txt, Value = notepad.exe 'Key = bmp, Value = paint.exe 'Key = dib, Value = paint.exe 'Key = rtf, Value = winword.exe 'Key = doc, Value = winword.exe 'Key = ht, Value = hypertrm.exe ' 'Value = notepad.exe 'Value = paint.exe 'Value = paint.exe 'Value = winword.exe 'Value = winword.exe 'Value = hypertrm.exe ' 'Key = txt 'Key = bmp 'Key = dib 'Key = rtf 'Key = doc 'Key = ht ' 'Remove("doc") 'Key "doc" is not found. '
using System; using System.Collections.Generic; public class Example { public static void Main() { // Create a new dictionary of strings, with string keys, // and access it through the IDictionary generic interface. IDictionary<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."); } // 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 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."); } // 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."); } // ContainsKey can be used to test keys before inserting // them. if (!openWith.ContainsKey("ht")) { openWith.Add("ht", "hypertrm.exe"); Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]); } // When you use foreach to enumerate dictionary elements, // the elements are retrieved as KeyValuePair objects. Console.WriteLine(); foreach( KeyValuePair<string, string> kvp in openWith ) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } // To get the values alone, use the Values property. ICollection<string> icoll = openWith.Values; // The elements of the ValueCollection are strongly typed // with the type that was specified for dictionary values. Console.WriteLine(); foreach( string s in icoll ) { Console.WriteLine("Value = {0}", s); } // To get the keys alone, use the Keys property. icoll = openWith.Keys; // The elements of the ValueCollection are strongly typed // with the type that was specified for dictionary values. Console.WriteLine(); foreach( string s in icoll ) { Console.WriteLine("Key = {0}", s); } // Use the Remove method to remove a key/value pair. Console.WriteLine("\nRemove(\"doc\")"); openWith.Remove("doc"); if (!openWith.ContainsKey("doc")) { Console.WriteLine("Key \"doc\" is not found."); } } } /* This code example produces the following output: An element with Key = "txt" already exists. For key = "rtf", value = wordpad.exe. For key = "rtf", value = winword.exe. Key = "tif" is not found. Key = "tif" is not found. Value added for key = "ht": hypertrm.exe Key = txt, Value = notepad.exe Key = bmp, Value = paint.exe Key = dib, Value = paint.exe Key = rtf, Value = winword.exe Key = doc, Value = winword.exe Key = ht, Value = hypertrm.exe Value = notepad.exe Value = paint.exe Value = paint.exe Value = winword.exe Value = winword.exe Value = hypertrm.exe Key = txt Key = bmp Key = dib Key = rtf Key = doc Key = ht Remove("doc") Key "doc" is not found. */
Plates-formesWindows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition
Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.
Outils (masquer)
S'enregistrer
Liste des Membres
Qui est en ligne?
FAQ