请单击以进行评分并提供反馈
全部折叠/全部展开 全部折叠
此页面仅适用于
Microsoft Visual Studio 2008/.NET Framework 3.5

同时提供下列产品的其他版本:
.NET Framework 类库
Dictionary<(Of <(TKey, TValue>)>)

更新:2007 年 11 月

表示键和值的集合。

命名空间:  System.Collections.Generic
程序集:  mscorlib(在 mscorlib.dll 中)
Visual Basic(声明)
<SerializableAttribute> _
<ComVisibleAttribute(False)> _
Public Class Dictionary(Of TKey, TValue) _
    Implements IDictionary(Of TKey, TValue), ICollection(Of KeyValuePair(Of TKey, TValue)),  _
    IEnumerable(Of KeyValuePair(Of TKey, TValue)), IDictionary,  _
    ICollection, IEnumerable, ISerializable, IDeserializationCallback
Visual Basic (用法)
Dim instance As Dictionary(Of TKey, TValue)
C#
[SerializableAttribute]
[ComVisibleAttribute(false)]
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, 
    ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
    IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback
Visual C++
[SerializableAttribute]
[ComVisibleAttribute(false)]
generic<typename TKey, typename TValue>
public ref class Dictionary : IDictionary<TKey, TValue>, 
    ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
    IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback
J#
J# 支持使用泛型 API,但是不支持新泛型 API 的声明。
JScript
JScript 不支持泛型类型或方法。

类型参数

TKey

字典中的键的类型。

TValue

字典中的值的类型。

Dictionary<(Of <(TKey, TValue>)>) 泛型类提供了从一组键到一组值的映射。字典中的每个添加项都由一个值及其相关联的键组成。通过键来检索值的速度是非常快的,接近于 O(1),这是因为 Dictionary<(Of <(TKey, TValue>)>) 类是作为一个哈希表来实现的。

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

检索速度取决于为 TKey 指定的类型的哈希算法的质量。

只要对象用作 Dictionary<(Of <(TKey, TValue>)>) 中的键,它就不能以任何影响其哈希值的方式更改。使用字典的相等比较器比较时,Dictionary<(Of <(TKey, TValue>)>) 中的任何键都必须是唯一的。键不能为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing,但是如果值类型 TValue 为引用类型,该值则可以为空。

Dictionary<(Of <(TKey, TValue>)>) 需要一个相等实现来确定键是否相等。可以使用一个接受 comparer 参数的构造函数来指定 IEqualityComparer<(Of <(T>)>) 泛型接口的实现;如果不指定实现,则使用默认的泛型相等比较器 EqualityComparer<(Of <(T>)>)..::.Default。如果类型 TKey 实现 System..::.IEquatable<(Of <(T>)>) 泛型接口,则默认相等比较器会使用该实现。

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

例如,您可以使用 StringComparer 类提供的不区分大小写的字符串比较器来创建带不区分大小写的字符串键的字典。

Dictionary<(Of <(TKey, TValue>)>) 的容量是 Dictionary<(Of <(TKey, TValue>)>) 可以包含的元素数。当向 Dictionary<(Of <(TKey, TValue>)>) 中添加元素时,将通过重新分配内部数组来根据需要自动增大容量。

对于枚举而言,字典中的每一项都被视为一个表示值及其键的 KeyValuePair<(Of <(TKey, TValue>)>) 结构进行处理。项返回的顺序未定义。

C# 语言的 foreach 语句(在 C++ 中为 for each,在 Visual Basic 中为 For Each)需要集合中每个元素的类型。由于 Dictionary<(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 语句是对枚举数的包装,只允许该枚举数读取集合,而不允许写入集合。

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

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

下面的代码示例创建一个空的带有字符串键的字符串 Dictionary<(Of <(TKey, TValue>)>),并使用 Add 方法添加一些元素。该示例演示在尝试添加重复的键时 Add 方法引发 ArgumentException

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

该示例演示,如果程序必须经常尝试词典中不存在的键值,如何使用 TryGetValue 方法作为更有效的检索值的方法,该示例还演示在调用 Add 方法之前如何使用 ContainsKey 方法来测试键是否存在。

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

最后,该示例演示 Remove 方法。

Visual Basic
Imports System
Imports System.Collections.Generic

Public Class Example

    Public Shared Sub Main() 

        ' 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 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 valueColl As _
            Dictionary(Of String, String).ValueCollection = _
            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  valueColl
            Console.WriteLine("Value = {0}", s)
        Next s

        ' To get the keys alone, use the Keys property.
        Dim keyColl As _
            Dictionary(Of String, String).KeyCollection = _
            openWith.Keys

        ' The elements of the KeyCollection are strongly typed
        ' with the type that was specified for dictionary keys.
        Console.WriteLine()
        For Each s As String In  keyColl
            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.
        //
        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.");
        }

        // 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.
        Dictionary<string, string>.ValueCollection valueColl =
            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 valueColl )
        {
            Console.WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        Dictionary<string, string>.KeyCollection keyColl =
            openWith.Keys;

        // The elements of the KeyCollection are strongly typed
        // with the type that was specified for dictionary keys.
        Console.WriteLine();
        foreach( string s in keyColl )
        {
            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.
 */
System..::.Object
  System.Collections.Generic..::.Dictionary<(Of <(TKey, TValue>)>)

此类型的公共静态(在 Visual Basic 中为 Shared)成员是线程安全的。但不能保证任何实例成员是线程安全的。

只要不修改该集合,Dictionary<(Of <(TKey, TValue>)>) 就可以同时支持多个阅读器。即便如此,从头到尾对一个集合进行枚举本质上并不是一个线程安全的过程。当出现枚举与写访问互相争用这种极少发生的情况时,必须在整个枚举过程中锁定集合。若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。

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
社区内容   什么是社区内容?
添加新内容 RSS  批注
Processing
© 2009 Microsoft Corporation 版权所有。 保留所有权利 | 商标 | 隐私权声明
Page view tracker