.NET Framework 类库
IDictionary<(Of <(TKey, TValue>)>) 接口

更新:2007 年 11 月

表示键/值对的泛型集合。

命名空间:  System.Collections.Generic
程序集:  mscorlib(在 mscorlib.dll 中)
语法

Visual Basic(声明)
Public Interface IDictionary(Of TKey, TValue) _
    Implements ICollection(Of KeyValuePair(Of TKey, TValue)),  _
    IEnumerable(Of KeyValuePair(Of TKey, TValue)), IEnumerable
Visual Basic (用法)
Dim instance As IDictionary(Of TKey, TValue)
C#
public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>, 
    IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
Visual C++
generic<typename TKey, typename TValue>
public interface class IDictionary : ICollection<KeyValuePair<TKey, TValue>>, 
    IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
J#
J# 支持使用泛型 API,但是不支持新泛型 API 的声明。
JScript
JScript 不支持泛型类型或方法。

类型参数

TKey

字典中键的类型。

TValue

字典中值的类型。

备注

IDictionary<(Of <(TKey, TValue>)>) 接口是键/值对的泛型集合的基接口。

每个元素都是一个存储在 KeyValuePair<(Of <(TKey, TValue>)>) 对象中的键/值对。

每一对都必须有唯一的键。实现在是否允许 keynullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing 方面有所不同。此值可以为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing,并且不必是唯一的。IDictionary<(Of <(TKey, TValue>)>) 接口允许对所包含的键和值进行枚举,但这并不意味着任何特定的排序顺序。

C# 语言中的 foreach 语句(在 Visual Basic 中为 For Each,在 C++ 中为 for each)需要集合中每个元素的类型。由于 IDictionary<(Of <(TKey, TValue>)>) 的每个元素都是一个键/值对,因此元素类型既不是键的类型,也不是值的类型。而是 KeyValuePair<(Of <(TKey, TValue>)>) 类型。例如:

C#
foreach (KeyValuePair<int, string> kvp in myDictionary) {...}
Visual C++
for each (KeyValuePair<int, String^> kvp in myDictionary) {...}
Visual Basic
For Each kvp As KeyValuePair(Of Integer, String) In myDictionary
    ...
Next kvp

foreach 语句是对枚举数的包装,它只允许从集合中读取,不允许写入集合。

s4ys34ea.alert_note(zh-cn,VS.90).gif说明:

由于键可以被继承而且它们的行为已更改,因此使用 Equals 方法进行的比较并不能保证其绝对唯一性。

对实现者的说明:

实现类必须有一种方式来对键进行比较。

示例

下面的代码示例创建一个没有字符串的空 Dictionary<(Of <(TKey, TValue>)>),其中有整数键,并且通过 IDictionary<(Of <(TKey, TValue>)>) 接口对其进行访问。

该代码示例使用 Add 方法添加一些元素。该示例演示,在尝试添加重复键时,Add 方法会引发 ArgumentException

该示例使用 Item 属性(在 C# 中为索引器)检索值,演示了在请求的键不存在时会引发 KeyNotFoundException,还演示了与键关联的值可以被替换。

该示例演示了:如果程序通常必须尝试不在字典中的键值,如何使用 TryGetValue 方法作为更有效的方式来检索值;另外还演示了:如何在调用 Add 方法之前使用 ContainsKey 方法来测试某个键是否存在。

最后,该示例演示如何枚举字典中的键和值,以及如何使用 Values 属性单独枚举值。

Visual Basic
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.
' 
C#
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.
 */
平台

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360

.NET Framework 和 .NET Compact Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求
版本信息

.NET Framework

受以下版本支持:3.5、3.0、2.0

.NET Compact Framework

受以下版本支持:3.5、2.0

XNA Framework

受以下版本支持:2.0、1.0
另请参见

参考

标记 :


Page view tracker