Dictionary<TKey,TValue> Class

定义

表示键和值的集合。 Represents a collection of keys and values.

[System.Runtime.InteropServices.ComVisible(false)]
public class Dictionary<TKey,TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IDictionary<TKey,TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
类型参数
TKey

字典中的键的类型。 The type of the keys in the dictionary.

TValue

字典中的值的类型。 The type of the values in the dictionary.

继承
Dictionary<TKey,TValue>
派生
属性
实现

示例

下面的代码示例创建一个空Dictionary<TKey,TValue>的字符串与字符串键,并使用Add方法来添加一些元素。The following code example creates an empty Dictionary<TKey,TValue> of strings with string keys and uses the Add method to add some elements. 该示例演示Add方法会抛出ArgumentException时尝试添加重复的键。The example demonstrates that the Add method throws an ArgumentException when attempting to add a duplicate key.

该示例使用Item[TKey]属性 (C# 中的索引器) 来检索值,从而演示KeyNotFoundException请求的键不存在,以及可以替换与某个键相关联的值时引发。The 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.

该示例演示如何使用TryGetValue方法作为更高效的方法来检索值,如果程序必须经常尝试在字典中,不并显示如何使用ContainsKey方法来测试某个键是否存在之前调用Add方法。The example 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, and it shows how to use the ContainsKey method to test whether a key exists before calling the Add method.

该示例演示如何枚举的键和值字典中的以及如何枚举密钥,并单独使用值Keys属性和Values属性。The example shows how to enumerate the keys and values in the dictionary and how to enumerate the keys and values alone using the Keys property and the Values property.

最后,该示例演示Remove方法。Finally, the example demonstrates the Remove method.

using namespace System;
using namespace System::Collections::Generic;

public ref class Example
{
public:
    static void Main()
    {
        // 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.");
        }

        // 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", 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();
        for each( 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();
        for each( 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();
        for each( 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.");
        }
    }
};

int main()
{
    Example::Main();
}

/* 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.
        //
        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.
 */
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.
' 

注解

Dictionary<TKey,TValue>泛型类提供从一组键到一组值的映射。The Dictionary<TKey,TValue> generic class provides a mapping from a set of keys to a set of values. 字典中的每个添加项都由一个值及其相关联的键组成。Each addition to the dictionary consists of a value and its associated key. 通过键来检索一个值是非常快,关闭到 o (1),因为Dictionary<TKey,TValue>类实现为哈希表。Retrieving a value by using its key is very fast, close to O(1), because the Dictionary<TKey,TValue> class is implemented as a hash table.

备注

检索的速度取决于为指定的类型的哈希算法的质量TKeyThe speed of retrieval depends on the quality of the hashing algorithm of the type specified for TKey.

只要使用对象作为一个密钥Dictionary<TKey,TValue>,不得更改任何方式影响其哈希值。As long as an object is used as a key in the Dictionary<TKey,TValue>, it must not change in any way that affects its hash value. 中的所有密钥Dictionary<TKey,TValue>必须是唯一根据字典的相等性比较器。Every key in a Dictionary<TKey,TValue> must be unique according to the dictionary's equality comparer. 密钥不能null,但值则可以为,如果类型值TValue是引用类型。A key cannot be null, but a value can be, if the value type TValue is a reference type.

Dictionary<TKey,TValue> 需要一个相等实现来确定键是否相等。Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. 您可以指定的实现IEqualityComparer<T>泛型接口使用的构造函数接受comparer参数; 如果未指定,默认泛型相等比较器实现EqualityComparer<T>.Default使用。You can specify an implementation of the IEqualityComparer<T> generic interface by using a constructor that accepts a comparer parameter; if you do not specify an implementation, the default generic equality comparer EqualityComparer<T>.Default is used. 如果类型TKey实现System.IEquatable<T>泛型接口的默认相等比较器使用该实现。If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation.

备注

例如,可以使用所提供的不区分大小写的字符串比较器StringComparer类来创建具有不区分大小写的字符串键的字典。For example, you can use the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys.

容量Dictionary<TKey,TValue>是元素数目Dictionary<TKey,TValue>可以容纳。The capacity of a Dictionary<TKey,TValue> is the number of elements the Dictionary<TKey,TValue> can hold. 元素添加到Dictionary<TKey,TValue>,自动增加容量所要求的重新分配内部数组。As elements are added to a Dictionary<TKey,TValue>, the capacity is automatically increased as required by reallocating the internal array.

对于非常大Dictionary<TKey,TValue>对象,可以通过设置增加到 20 亿元素在 64 位系统上的最大容量enabled到的配置元素的特性true在运行时环境中。For very large Dictionary<TKey,TValue> objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the configuration element to true in the run-time environment.

对于枚举而言,字典中的每个项都会被视为KeyValuePair<TKey,TValue>结构,它表示包含值和其键。For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey,TValue> structure representing a value and its key. 返回项的顺序是未定义。The order in which the items are returned is undefined.

foreach C# 语言的语句 (for each c + + 中For Each在 Visual Basic 中) 返回集合中的元素的类型的对象。The foreach statement of the C# language (for each in C++, For Each in Visual Basic) returns an object of the type of the elements in the collection. 由于Dictionary<TKey,TValue>是一系列密钥和值、 元素类型不是键的类型或值的类型。Since the Dictionary<TKey,TValue> is a collection of keys and values, the element type is not the type of the key or the type of the value. 相反,元素类型是KeyValuePair<TKey,TValue>的密钥类型和值类型。Instead, the element type is a KeyValuePair<TKey,TValue> of the key type and the value type. 例如:For example:

for each(KeyValuePair<String^, String^> kvp in myDictionary)
{
    Console::WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
foreach( KeyValuePair<string, string> kvp in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
For Each kvp As KeyValuePair(Of String, String) In myDictionary
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value)
Next kvp

foreach语句是枚举器,它允许仅从该集合进行读取,不向其写入的包装。The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it.

备注

因为密钥可以被继承,但不能更改其行为,使用的比较保证其绝对唯一性Equals方法。Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the Equals method.

构造函数

Dictionary<TKey,TValue>()

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有默认的初始容量,并使用键类型的默认相等比较器。 Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并为键类型使用默认的相等比较器。 Initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the default equality comparer for the key type.

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并使用指定的 IEqualityComparer<T> Initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the specified IEqualityComparer<T>.

Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)
Dictionary<TKey,TValue>(IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有默认的初始容量,并使用指定的 IEqualityComparer<T> Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the specified IEqualityComparer<T>.

Dictionary<TKey,TValue>(Int32)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有指定的初始容量,并为键类型使用默认的相等比较器。 Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the default equality comparer for the key type.

Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有指定的初始容量,并使用指定的 IEqualityComparer<T> Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the specified IEqualityComparer<T>.

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

用序列化数据初始化 Dictionary<TKey,TValue> 类的新实例。 Initializes a new instance of the Dictionary<TKey,TValue> class with serialized data.

属性

Comparer

获取用于确定字典中的键是否相等的 IEqualityComparer<T> Gets the IEqualityComparer<T> that is used to determine equality of keys for the dictionary.

Count

获取包含在 Dictionary<TKey,TValue> 中的键/值对的数目。 Gets the number of key/value pairs contained in the Dictionary<TKey,TValue>.

Item[TKey]

获取或设置与指定的键相关联的值。 Gets or sets the value associated with the specified key.

Keys

获取包含 Dictionary<TKey,TValue> 中的键的集合。 Gets a collection containing the keys in the Dictionary<TKey,TValue>.

Values

获取包含 Dictionary<TKey,TValue> 中的值的集合。 Gets a collection containing the values in the Dictionary<TKey,TValue>.

方法

Add(TKey, TValue)

将指定的键和值添加到字典中。 Adds the specified key and value to the dictionary.

Clear()

Dictionary<TKey,TValue> 中移除所有的键和值。 Removes all keys and values from the Dictionary<TKey,TValue>.

ContainsKey(TKey)

确定 Dictionary<TKey,TValue> 是否包含指定的键。 Determines whether the Dictionary<TKey,TValue> contains the specified key.

ContainsValue(TValue)

确定 Dictionary<TKey,TValue> 是否包含特定值。 Determines whether the Dictionary<TKey,TValue> contains a specific value.

EnsureCapacity(Int32)
Equals(Object)

确定指定的对象是否等于当前对象。 Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator()

返回循环访问 Dictionary<TKey,TValue> 的枚举数。 Returns an enumerator that iterates through the Dictionary<TKey,TValue>.

GetHashCode()

作为默认哈希函数。 Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext)

实现 ISerializable 接口,并返回序列化 Dictionary<TKey,TValue> 实例所需的数据。 Implements the ISerializable interface and returns the data needed to serialize the Dictionary<TKey,TValue> instance.

GetType()

获取当前实例的 Type Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

创建当前 Object 的浅表副本。 Creates a shallow copy of the current Object.

(Inherited from Object)
OnDeserialization(Object)

实现 ISerializable 接口,并在完成反序列化之后引发反序列化事件。 Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

Remove(TKey)

Dictionary<TKey,TValue> 中移除所指定的键的值。 Removes the value with the specified key from the Dictionary<TKey,TValue>.

Remove(TKey, TValue)
ToString()

返回表示当前对象的字符串。 Returns a string that represents the current object.

(Inherited from Object)
TrimExcess()
TrimExcess(Int32)
TryAdd(TKey, TValue)
TryGetValue(TKey, TValue)

获取与指定的键相关联的值。 Gets the value associated with the specified key.

显式界面实现

ICollection.CopyTo(Array, Int32)

从指定的数组索引开始,将 ICollection<T> 中的元素复制到一个数组中。 Copies the elements of the ICollection<T> to an array, starting at the specified array index.

ICollection.IsSynchronized

获取一个值,该值指示是否同步对 ICollection 的访问(线程安全)。 Gets a value indicating whether access to the ICollection is synchronized (thread safe).

ICollection.SyncRoot

获取可用于同步对 ICollection 的访问的对象。 Gets an object that can be used to synchronize access to the ICollection.

ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey,TValue>)
ICollection<KeyValuePair<TKey,TValue>>.Contains(KeyValuePair<TKey,TValue>)
ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[], Int32)
ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly
ICollection<KeyValuePair<TKey,TValue>>.Remove(KeyValuePair<TKey,TValue>)
IDictionary.Add(Object, Object)

将指定的键和值添加到字典中。 Adds the specified key and value to the dictionary.

IDictionary.Contains(Object)

确定 IDictionary 是否包含具有指定键的元素。 Determines whether the IDictionary contains an element with the specified key.

IDictionary.GetEnumerator()

返回 IDictionaryEnumeratorIDictionary Returns an IDictionaryEnumerator for the IDictionary.

IDictionary.IsFixedSize

获取一个值,该值指示 IDictionary 是否具有固定大小。 Gets a value indicating whether the IDictionary has a fixed size.

IDictionary.IsReadOnly

获取一个值,该值指示 IDictionary 是否为只读。 Gets a value indicating whether the IDictionary is read-only.

IDictionary.Item[Object]

获取或设置具有指定键的值。 Gets or sets the value with the specified key.

IDictionary.Keys

获取包含 ICollection 的键的 IDictionary Gets an ICollection containing the keys of the IDictionary.

IDictionary.Remove(Object)

IDictionary 中移除带有指定键的元素。 Removes the element with the specified key from the IDictionary.

IDictionary.Values

获取包含 ICollection 中的值的 IDictionary Gets an ICollection containing the values in the IDictionary.

IDictionary<TKey,TValue>.Keys
IDictionary<TKey,TValue>.Values
IEnumerable.GetEnumerator()

返回一个循环访问集合的枚举器。 Returns an enumerator that iterates through the collection.

IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator()
IReadOnlyDictionary<TKey,TValue>.Keys
IReadOnlyDictionary<TKey,TValue>.Values

适用于

线程安全性

一个Dictionary<TKey,TValue>,只要不修改该集合可以同时支持多个读取器。 A Dictionary<TKey,TValue> can support multiple readers concurrently, as long as the collection is not modified. 即便如此,枚举整个集合本质上不是线程安全的过程。 Even so, enumerating through a collection is intrinsically not a thread-safe procedure. 枚举与写访问的竞争的极少数情况下,必须在整个枚举期间锁定集合。 In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. 若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。 To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. 有关线程安全的替代,请参阅 ConcurrentDictionary<TKey,TValue> 类或 ImmutableDictionary<TKey,TValue> 类。 For thread-safe alternatives, see the ConcurrentDictionary<TKey,TValue> class or ImmutableDictionary<TKey,TValue> class. 公共静态 (Shared在 Visual Basic 中) 的此类型的成员是线程安全。 Public static (Shared in Visual Basic) members of this type are thread safe.

另请参阅