Dictionary<TKey,TValue> Dictionary<TKey,TValue> Dictionary<TKey,TValue> Dictionary<TKey,TValue> Constructors

定义

重载

Dictionary<TKey,TValue>() Dictionary<TKey,TValue>() 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>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) 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>(IEnumerable<KeyValuePair<TKey,TValue>>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
Dictionary<TKey,TValue>(IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEqualityComparer<TKey>) Dictionary<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>(Int32) Dictionary<TKey,TValue>(Int32) 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>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) 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>>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)
Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) 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>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

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

Dictionary<TKey,TValue>() Dictionary<TKey,TValue>() 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.

public:
 Dictionary();
public Dictionary ();
Public Sub New ()

示例

备注

本文中的一些 C# 示例在 Try.NET 内联代码运行程序和演练环境中运行。Some of the C# examples in this article run in the Try.NET inline code runner and playground. 选择“运行” 按钮(若有),在交互式窗口中运行示例。When present, select the Run button to run an example in an interactive window. 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码 。Once you execute the code, you can modify it and run the modified code by selecting Run again. 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

下面的代码示例使用字符串键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. 该示例演示AddArgumentException在尝试添加重复键时方法引发。The example demonstrates that the Add method throws an ArgumentException when attempting to add a duplicate key.

此代码示例是为Dictionary<TKey,TValue>类提供的更大示例的一部分。This code example is part of a larger example provided for the Dictionary<TKey,TValue> class.

// 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.");
}
// 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.");
}
' 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

注解

根据默认的相等Dictionary<TKey,TValue>比较器,中的每个键都必须是唯一的。Every key in a Dictionary<TKey,TValue> must be unique according to the default equality comparer.

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

备注

如果可以估计集合的大小,则使用指定初始容量的构造函数无需在向中添加元素Dictionary<TKey,TValue>时执行多个大小调整操作。If you can estimate the size of the collection, using a constructor that specifies the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Dictionary<TKey,TValue>.

此构造函数的运算复杂度为 O (1)。This constructor is an O(1) operation.

另请参阅

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) 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.

public:
 Dictionary(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary);
public Dictionary (System.Collections.Generic.IDictionary<TKey,TValue> dictionary);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue))

参数

异常

dictionary 包含一个或多个重复键。dictionary contains one or more duplicate keys.

示例

下面的代码示例演示如何使用Dictionary<TKey,TValue>(IEqualityComparer<TKey>)构造函数来Dictionary<TKey,TValue>初始化具有其他字典中已排序内容的。The following code example shows how to use the Dictionary<TKey,TValue>(IEqualityComparer<TKey>) constructor to initialize a Dictionary<TKey,TValue> with sorted content from another dictionary. 此代码示例创建一个SortedDictionary<TKey,TValue> ,并用随机顺序填充数据,然后将SortedDictionary<TKey,TValue>传递到Dictionary<TKey,TValue>(IEqualityComparer<TKey>)构造函数,从而创建Dictionary<TKey,TValue>排序的。The code example creates a SortedDictionary<TKey,TValue> and populates it with data in random order, then passes the SortedDictionary<TKey,TValue> to the Dictionary<TKey,TValue>(IEqualityComparer<TKey>) constructor, creating a Dictionary<TKey,TValue> that is sorted. 如果需要生成一个在某个时间点变为静态的已排序字典,这会很有用;将数据从SortedDictionary<TKey,TValue>复制Dictionary<TKey,TValue>到可提高检索速度。This is useful if you need to build a sorted dictionary that at some point becomes static; copying the data from a SortedDictionary<TKey,TValue> to a Dictionary<TKey,TValue> improves retrieval speed.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new sorted dictionary of strings, with string 
        // keys.
        SortedDictionary<string, string> openWith = 
            new SortedDictionary<string, string>();
        
        // Add some elements to the dictionary. 
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");
        
        // Create a Dictionary of strings with string keys, and 
        // initialize it with the contents of the sorted dictionary.
        Dictionary<string, string> copy = 
            new Dictionary<string, string>(openWith);

        // List the contents of the copy.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in copy )
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
               kvp.Key, kvp.Value);
        }
    }
}

/* This code example produces the following output:

Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = wordpad.exe
Key = txt, Value = notepad.exe
 */
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new sorted dictionary of strings, with string 
        ' keys.
        Dim openWith As New SortedDictionary(Of String, String)
        
        ' Add some elements to the sorted dictionary. 
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")
        
        ' Create a Dictionary of strings with string keys, and 
        ' initialize it with the contents of the sorted dictionary.
        Dim copy As New Dictionary(Of String, String)(openWith)

        ' List the contents of the copy.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In copy
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

    End Sub

End Class

' This code example produces the following output:
'
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe

注解

根据默认的相等Dictionary<TKey,TValue>比较器,中的每个键都必须是唯一的; 同样,根据dictionary默认的相等比较器,源中的每个键都必须是唯一的。Every key in a Dictionary<TKey,TValue> must be unique according to the default equality comparer; likewise, every key in the source dictionary must also be unique according to the default equality comparer.

Dictionary<TKey,TValue>的初始容量足以包含中dictionary的所有元素。The initial capacity of the new Dictionary<TKey,TValue> is large enough to contain all the elements in dictionary.

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

此构造函数的运算复杂度为 O (n),其中 n 是中dictionary的元素数目。This constructor is an O(n) operation, where n is the number of elements in dictionary.

另请参阅

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

public:
 Dictionary(System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>> ^ collection);
public Dictionary (System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>> collection);
new System.Collections.Generic.Dictionary<'Key, 'Value> : seq<System.Collections.Generic.KeyValuePair<'Key, 'Value>> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (collection As IEnumerable(Of KeyValuePair(Of TKey, TValue)))

参数

collection
IEnumerable<KeyValuePair<TKey,TValue>>

Dictionary<TKey,TValue>(IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEqualityComparer<TKey>) Dictionary<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>.

public:
 Dictionary(System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary (System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (comparer As IEqualityComparer(Of TKey))

参数

comparer
IEqualityComparer<TKey>

比较键时要使用的 IEqualityComparer<T> 实现,或者为 null,以便为键类型使用默认的 EqualityComparer<T>The IEqualityComparer<T> implementation to use when comparing keys, or null to use the default EqualityComparer<T> for the type of the key.

示例

下面的代码示例使用当前Dictionary<TKey,TValue>区域性的不区分大小写的相等比较器创建一个。The following code example creates a Dictionary<TKey,TValue> with a case-insensitive equality comparer for the current culture. 该示例将添加四个元素,其中一些包含小写键,一些具有大写键。The example adds four elements, some with lower-case keys and some with upper-case keys. 然后,该示例尝试添加一个元素,该元素具有仅大小写不同于现有密钥的键,并捕获产生的异常,并显示一条错误消息。The example then attempts to add an element with a key that differs from an existing key only by case, catches the resulting exception, and displays an error message. 最后,此示例将在字典中显示元素。Finally, the example displays the elements in the dictionary.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new Dictionary of strings, with string keys 
        // and a case-insensitive comparer for the current culture.
        Dictionary<string, string> openWith = 
                      new Dictionary<string, string>( 
                          StringComparer.CurrentCultureIgnoreCase);
        
        // Add some elements to the dictionary.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("DIB", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // Try to add a fifth element with a key that is the same 
        // except for case; this would be allowed with the default
        // comparer.
        try
        {
            openWith.Add("BMP", "paint.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("\nBMP is already in the dictionary.");
        }
        
        // List the contents of the sorted dictionary.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, 
                kvp.Value);
        }
    }
}

/* This code example produces the following output:

BMP is already in the dictionary.

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = DIB, Value = paint.exe
Key = rtf, Value = wordpad.exe
 */
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new Dictionary of strings, with string keys 
        ' and a case-insensitive comparer for the current culture.
        Dim openWith As New Dictionary(Of String, String)( _
            StringComparer.CurrentCultureIgnoreCase)
        
        ' Add some elements to the dictionary. 
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("DIB", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")

        ' Try to add a fifth element with a key that is the same 
        ' except for case; this would be allowed with the default
        ' comparer.
        Try
            openWith.Add("BMP", "paint.exe")
        Catch ex As ArgumentException
            Console.WriteLine(vbLf & "BMP is already in the dictionary.")
        End Try
        
        ' List the contents of the dictionary.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

    End Sub

End Class

' This code example produces the following output:
'
'BMP is already in the dictionary.
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe

注解

将此构造函数与StringComparer类提供的不区分大小写的字符串比较器结合使用,以创建具有不区分大小写的字符串键的字典。Use this constructor with the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys.

根据指定的比较Dictionary<TKey,TValue>器,中的每个键都必须是唯一的。Every key in a Dictionary<TKey,TValue> must be unique according to the specified comparer.

Dictionary<TKey,TValue>需要一个相等实现来确定键是否相等。Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. 如果comparer EqualityComparer<T>.Defaultnull,则此构造函数使用默认的泛型相等比较器。If comparer is null, this constructor uses the default generic equality comparer, EqualityComparer<T>.Default. 如果类型TKey System.IEquatable<T>实现泛型接口,则默认的相等比较器将使用该实现。If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation.

备注

如果可以估计集合的大小,则使用指定初始容量的构造函数无需在向中添加元素Dictionary<TKey,TValue>时执行多个大小调整操作。If you can estimate the size of the collection, using a constructor that specifies the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Dictionary<TKey,TValue>.

此构造函数的运算复杂度为 O (1)。This constructor is an O(1) operation.

另请参阅

Dictionary<TKey,TValue>(Int32) Dictionary<TKey,TValue>(Int32) Dictionary<TKey,TValue>(Int32) 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.

public:
 Dictionary(int capacity);
public Dictionary (int capacity);
new System.Collections.Generic.Dictionary<'Key, 'Value> : int -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (capacity As Integer)

参数

capacity
Int32 Int32 Int32 Int32

Dictionary<TKey,TValue> 可包含的初始元素数。The initial number of elements that the Dictionary<TKey,TValue> can contain.

异常

示例

下面的代码示例创建一个初始容量为4的字典,并使用4个条目来填充它。The following code example creates a dictionary with an initial capacity of 4 and populates it with 4 entries.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys and
        // an initial capacity of 4.
        Dictionary<string, string> openWith = 
                               new Dictionary<string, string>(4);
        
        // Add 4 elements to the dictionary. 
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");
        
        // List the contents of the dictionary.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
               kvp.Key, kvp.Value);
        }
    }
}

/* This code example produces the following output:

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = wordpad.exe
 */
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new dictionary of strings, with string keys and
        ' an initial capacity of 4.
        Dim openWith As New Dictionary(Of String, String)(4)
        
        ' Add 4 elements to the dictionary. 
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")
        
        ' List the contents of the dictionary.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

    End Sub

End Class

' This code example produces the following output:
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = wordpad.exe

注解

根据默认的相等Dictionary<TKey,TValue>比较器,中的每个键都必须是唯一的。Every key in a Dictionary<TKey,TValue> must be unique according to the default equality comparer.

的容量Dictionary<TKey,TValue>是在需要调整大小之前可以添加到的Dictionary<TKey,TValue>元素的数目。The capacity of a Dictionary<TKey,TValue> is the number of elements that can be added to the Dictionary<TKey,TValue> before resizing is necessary. 当向添加元素时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>时执行多个大小调整操作。If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Dictionary<TKey,TValue>.

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

此构造函数的运算复杂度为 O (1)。This constructor is an O(1) operation.

另请参阅

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) 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>.

public:
 Dictionary(System::Collections::Generic::IDictionary<TKey, TValue> ^ dictionary, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary (System.Collections.Generic.IDictionary<TKey,TValue> dictionary, System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Collections.Generic.IDictionary<'Key, 'Value> * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (dictionary As IDictionary(Of TKey, TValue), comparer As IEqualityComparer(Of TKey))

参数

comparer
IEqualityComparer<TKey>

比较键时要使用的 IEqualityComparer<T> 实现,或者为 null,以便为键类型使用默认的 EqualityComparer<T>The IEqualityComparer<T> implementation to use when comparing keys, or null to use the default EqualityComparer<T> for the type of the key.

异常

dictionary 包含一个或多个重复键。dictionary contains one or more duplicate keys.

示例

下面的代码示例演示如何使用Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)构造函数来初始化另一字典中具有不区分大小写的排序内容的。 Dictionary<TKey,TValue>The following code example shows how to use the Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) constructor to initialize a Dictionary<TKey,TValue> with case-insensitive sorted content from another dictionary. 此代码示例创建一个SortedDictionary<TKey,TValue>具有不区分大小写的比较器,并用随机顺序填充数据,然后将SortedDictionary<TKey,TValue>传递到Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)构造函数,并将不区分Dictionary<TKey,TValue>大小写的相等比较器与已排序。The code example creates a SortedDictionary<TKey,TValue> with a case-insensitive comparer and populates it with data in random order, then passes the SortedDictionary<TKey,TValue> to the Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) constructor, along with a case-insensitive equality comparer, creating a Dictionary<TKey,TValue> that is sorted. 如果需要生成一个在某个时间点变为静态的已排序字典,这会很有用;将数据从SortedDictionary<TKey,TValue>复制Dictionary<TKey,TValue>到可提高检索速度。This is useful if you need to build a sorted dictionary that at some point becomes static; copying the data from a SortedDictionary<TKey,TValue> to a Dictionary<TKey,TValue> improves retrieval speed.

备注

当你使用不区分大小写的比较器创建一个新的字典,并使用使用区分大小写的比较器的字典中的项进行填充时,如本示例中所示,如果输入字典具有仅大小写不同的键,则会出现异常。When you create a new dictionary with a case-insensitive comparer and populate it with entries from a dictionary that uses a case-sensitive comparer, as in this example, an exception occurs if the input dictionary has keys that differ only by case.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new sorted dictionary of strings, with string 
        // keys and a case-insensitive comparer.
        SortedDictionary<string, string> openWith = 
                new SortedDictionary<string, string>(
                    StringComparer.CurrentCultureIgnoreCase);
        
        // Add some elements to the dictionary. 
        openWith.Add("txt", "notepad.exe");
        openWith.Add("Bmp", "paint.exe");
        openWith.Add("DIB", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");
        
        // Create a Dictionary of strings with string keys and a
        // case-insensitive equality comparer, and initialize it
        // with the contents of the sorted dictionary.
        Dictionary<string, string> copy = 
                new Dictionary<string, string>(openWith, 
                    StringComparer.CurrentCultureIgnoreCase);

        // List the contents of the copy.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in copy )
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
               kvp.Key, kvp.Value);
        }
    }
}

/* This code example produces the following output:

Key = Bmp, Value = paint.exe
Key = DIB, Value = paint.exe
Key = rtf, Value = wordpad.exe
Key = txt, Value = notepad.exe
 */
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new sorted dictionary of strings, with string 
        ' keys and a case-insensitive comparer.
        Dim openWith As New SortedDictionary(Of String, String)( _
            StringComparer.CurrentCultureIgnoreCase)
        
        ' Add some elements to the sorted dictionary. 
        openWith.Add("txt", "notepad.exe")
        openWith.Add("Bmp", "paint.exe")
        openWith.Add("DIB", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")
        
        ' Create a Dictionary of strings with string keys and a 
        ' case-insensitive equality comparer, and initialize it
        ' with the contents of the sorted dictionary.
        Dim copy As New Dictionary(Of String, String)(openWith, _
            StringComparer.CurrentCultureIgnoreCase)

        ' List the contents of the copy.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In copy
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

    End Sub

End Class

' This code example produces the following output:
'
'Key = Bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe

注解

将此构造函数与StringComparer类提供的不区分大小写的字符串比较器结合使用,以创建具有不区分大小写的字符串键的字典。Use this constructor with the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys.

根据指定的比较Dictionary<TKey,TValue>器,中的每个键都必须是唯一的; 同样,根据dictionary指定的比较器,源中的每个键都必须是唯一的。Every key in a Dictionary<TKey,TValue> must be unique according to the specified comparer; likewise, every key in the source dictionary must also be unique according to the specified comparer.

备注

例如,如果comparerStringComparer类提供的不区分大小写的字符串比较器之一,并且dictionary不使用不区分大小写的比较器键,则可能会发生重复键。For example, duplicate keys can occur if comparer is one of the case-insensitive string comparers provided by the StringComparer class and dictionary does not use a case-insensitive comparer key.

Dictionary<TKey,TValue>的初始容量足以包含中dictionary的所有元素。The initial capacity of the new Dictionary<TKey,TValue> is large enough to contain all the elements in dictionary.

Dictionary<TKey,TValue>需要一个相等实现来确定键是否相等。Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. 如果comparer EqualityComparer<T>.Defaultnull,则此构造函数使用默认的泛型相等比较器。If comparer is null, this constructor uses the default generic equality comparer, EqualityComparer<T>.Default. 如果类型TKey System.IEquatable<T>实现泛型接口,则默认的相等比较器将使用该实现。If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation.

此构造函数是一个 On()运算, n其中是中dictionary的元素数。This constructor is an O(n) operation, where n is the number of elements in dictionary.

另请参阅

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

public:
 Dictionary(System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>> ^ collection, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary (System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : seq<System.Collections.Generic.KeyValuePair<'Key, 'Value>> * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (collection As IEnumerable(Of KeyValuePair(Of TKey, TValue)), comparer As IEqualityComparer(Of TKey))

参数

collection
IEnumerable<KeyValuePair<TKey,TValue>>
comparer
IEqualityComparer<TKey>

Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) 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>.

public:
 Dictionary(int capacity, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
public Dictionary (int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer);
new System.Collections.Generic.Dictionary<'Key, 'Value> : int * System.Collections.Generic.IEqualityComparer<'Key> -> System.Collections.Generic.Dictionary<'Key, 'Value>
Public Sub New (capacity As Integer, comparer As IEqualityComparer(Of TKey))

参数

capacity
Int32 Int32 Int32 Int32

Dictionary<TKey,TValue> 可包含的初始元素数。The initial number of elements that the Dictionary<TKey,TValue> can contain.

comparer
IEqualityComparer<TKey>

比较键时要使用的 IEqualityComparer<T> 实现,或者为 null,以便为键类型使用默认的 EqualityComparer<T>The IEqualityComparer<T> implementation to use when comparing keys, or null to use the default EqualityComparer<T> for the type of the key.

异常

示例

下面的代码示例创建一个Dictionary<TKey,TValue>初始容量为5的,以及当前区域性的不区分大小写的相等比较器。The following code example creates a Dictionary<TKey,TValue> with an initial capacity of 5 and a case-insensitive equality comparer for the current culture. 该示例将添加四个元素,其中一些包含小写键,一些具有大写键。The example adds four elements, some with lower-case keys and some with upper-case keys. 然后,该示例尝试添加一个元素,该元素具有仅大小写不同于现有密钥的键,并捕获产生的异常,并显示一条错误消息。The example then attempts to add an element with a key that differs from an existing key only by case, catches the resulting exception, and displays an error message. 最后,此示例将在字典中显示元素。Finally, the example displays the elements in the dictionary.

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys, an
        // initial capacity of 5, and a case-insensitive equality 
        // comparer.
        Dictionary<string, string> openWith = 
                      new Dictionary<string, string>(5, 
                          StringComparer.CurrentCultureIgnoreCase);
        
        // Add 4 elements to the dictionary. 
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("DIB", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // Try to add a fifth element with a key that is the same 
        // except for case; this would be allowed with the default
        // comparer.
        try
        {
            openWith.Add("BMP", "paint.exe");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("\nBMP is already in the dictionary.");
        }
        
        // List the contents of the dictionary.
        Console.WriteLine();
        foreach( KeyValuePair<string, string> kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, 
                kvp.Value);
        }
    }
}

/* This code example produces the following output:

BMP is already in the dictionary.

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = DIB, Value = paint.exe
Key = rtf, Value = wordpad.exe
 */
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new Dictionary of strings, with string keys, an
        ' initial capacity of 5, and a case-insensitive equality
        ' comparer.
        Dim openWith As New Dictionary(Of String, String)(5, _
            StringComparer.CurrentCultureIgnoreCase)
        
        ' Add 4 elements to the dictionary. 
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("DIB", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")

        ' Try to add a fifth element with a key that is the same 
        ' except for case; this would be allowed with the default
        ' comparer.
        Try
            openWith.Add("BMP", "paint.exe")
        Catch ex As ArgumentException
            Console.WriteLine(vbLf & "BMP is already in the dictionary.")
        End Try
        
        ' List the contents of the dictionary.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

    End Sub

End Class

' This code example produces the following output:
'
'BMP is already in the dictionary.
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = DIB, Value = paint.exe
'Key = rtf, Value = wordpad.exe

注解

将此构造函数与StringComparer类提供的不区分大小写的字符串比较器结合使用,以创建具有不区分大小写的字符串键的字典。Use this constructor with the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys.

根据指定的比较Dictionary<TKey,TValue>器,中的每个键都必须是唯一的。Every key in a Dictionary<TKey,TValue> must be unique according to the specified comparer.

的容量Dictionary<TKey,TValue>是在需要调整大小之前可以添加到的Dictionary<TKey,TValue>元素的数目。The capacity of a Dictionary<TKey,TValue> is the number of elements that can be added to the Dictionary<TKey,TValue> before resizing is necessary. 当向添加元素时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>时执行多个大小调整操作。If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Dictionary<TKey,TValue>.

Dictionary<TKey,TValue>需要一个相等实现来确定键是否相等。Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. 如果comparer EqualityComparer<T>.Defaultnull,则此构造函数使用默认的泛型相等比较器。If comparer is null, this constructor uses the default generic equality comparer, EqualityComparer<T>.Default. 如果类型TKey System.IEquatable<T>实现泛型接口,则默认的相等比较器将使用该实现。If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation.

此构造函数的运算复杂度为 O (1)。This constructor is an O(1) operation.

另请参阅

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

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

protected:
 Dictionary(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected Dictionary (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.Dictionary<'Key, 'Value>
Protected Sub New (info As SerializationInfo, context As StreamingContext)

参数

info
SerializationInfo SerializationInfo SerializationInfo SerializationInfo

一个 SerializationInfo 对象包含序列化 Dictionary<TKey,TValue> 所需的信息。A SerializationInfo object containing the information required to serialize the Dictionary<TKey,TValue>.

context
StreamingContext StreamingContext StreamingContext StreamingContext

StreamingContext 结构,该结构包含与 Dictionary<TKey,TValue> 相关联的序列化流的源和目标。A StreamingContext structure containing the source and destination of the serialized stream associated with the Dictionary<TKey,TValue>.

注解

在反序列化过程中调用此构造函数来重建通过流传输的对象。This constructor is called during deserialization to reconstitute an object transmitted over a stream. 有关详细信息,请参阅XML 和 SOAP 序列化For more information, see XML and SOAP Serialization.

另请参阅

适用于