Dictionary<TKey,TValue> 构造函数

定义

初始化 Dictionary<TKey,TValue> 类的新实例。

重载

Dictionary<TKey,TValue>()

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有默认的初始容量,并使用键类型的默认相等比较器。

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

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并为键类型使用默认的相等比较器。

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

初始化 Dictionary<TKey,TValue> 类的新实例,该类包含从指定的 IEnumerable<T> 中复制的元素。

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

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空,具有默认的初始容量并使用指定的 IEqualityComparer<T>

Dictionary<TKey,TValue>(Int32)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有指定的初始容量,并为键类型使用默认的相等比较器。

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

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并使用指定的 IEqualityComparer<T>

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

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IEnumerable<T> 中复制的元素并使用指定的 IEqualityComparer<T>

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

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空,具有指定的初始容量并使用指定的 IEqualityComparer<T>

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)
已过时.

用序列化数据初始化 Dictionary<TKey,TValue> 类的新实例。

Dictionary<TKey,TValue>()

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有默认的初始容量,并使用键类型的默认相等比较器。

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

示例

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

此代码示例是为 Dictionary<TKey,TValue> 类提供的一个更大示例的一部分。

// 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> 中的每个键都必须是唯一的。

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

注意

如果可以估计集合的大小,则使用指定初始容量的构造函数无需在向 Dictionary<TKey,TValue>中添加元素时执行大量大小调整操作。

此构造函数是 O (1) 操作。

另请参阅

适用于

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

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并为键类型使用默认的相等比较器。

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
IDictionary<TKey,TValue>

IDictionary<TKey,TValue>,它的元素被复制到新 Dictionary<TKey,TValue>

例外

dictionary 上声明的默认值为 null

dictionary 包含一个或多个重复键。

示例

下面的代码示例演示如何使用 Dictionary<TKey,TValue>(IEqualityComparer<TKey>) 构造函数通过另一个 Dictionary<TKey,TValue> 字典中的已排序内容初始化 。 该代码示例创建 并SortedDictionary<TKey,TValue>按随机顺序填充数据,然后将 传递给SortedDictionary<TKey,TValue>Dictionary<TKey,TValue>(IEqualityComparer<TKey>)构造函数,创建Dictionary<TKey,TValue>排序的 。 如果需要生成在某个时间点变为静态的排序字典,这非常有用;将数据从 SortedDictionary<TKey,TValue> 复制到 可以提高 Dictionary<TKey,TValue> 检索速度。

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 中的每个键也必须根据默认相等比较器是唯一的。

Dictionary<TKey,TValue> 的初始容量足以包含 中的所有 dictionary元素。

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

此构造函数是一个 O (n) 操作,其中 n 是 中的 dictionary元素数。

另请参阅

适用于

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

初始化 Dictionary<TKey,TValue> 类的新实例,该类包含从指定的 IEnumerable<T> 中复制的元素。

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>>

IEnumerable<T>,它的元素被复制到新 Dictionary<TKey,TValue>

例外

collection 上声明的默认值为 null

collection 包含一个或多个重复的键。

适用于

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

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空,具有默认的初始容量并使用指定的 IEqualityComparer<T>

public:
 Dictionary(System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
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>

示例

下面的代码示例为当前区域性创建 Dictionary<TKey,TValue> 一个不区分大小写的相等比较器。 该示例添加了四个元素,其中一些具有小写键,一些元素使用大写键。 然后,该示例尝试添加一个元素,该元素的键仅在大小写上与现有键不同,捕获生成的异常并显示错误消息。 最后,该示例显示字典中的元素。

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 不区分大小写的字符串比较器一起使用,以创建具有不区分大小写的字符串键的字典。

根据指定的比较器, Dictionary<TKey,TValue> 中的每个键都必须是唯一的。

Dictionary<TKey,TValue> 需要相等实现来确定键是否相等。 如果 comparernull,则此构造函数使用默认的泛型相等比较器 EqualityComparer<T>.Default。 如果 类型 TKey 实现 System.IEquatable<T> 泛型接口,则默认相等比较器使用该实现。

注意

如果可以估计集合的大小,则使用指定初始容量的构造函数无需在向 Dictionary<TKey,TValue>中添加元素时执行大量大小调整操作。

此构造函数是 O (1) 操作。

另请参阅

适用于

Dictionary<TKey,TValue>(Int32)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有指定的初始容量,并为键类型使用默认的相等比较器。

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

Dictionary<TKey,TValue> 可包含的初始元素数。

例外

capacity 小于 0。

示例

下面的代码示例创建一个初始容量为 4 的字典,并使用 4 个条目填充该字典。

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> 中的每个键都必须是唯一的。

Dictionary<TKey,TValue> 容量是在需要调整大小之前可以添加到 的 Dictionary<TKey,TValue> 元素数。 将元素添加到 时 Dictionary<TKey,TValue>,通过重新分配内部数组,容量会根据需要自动增加。

如果可以估计集合的大小,则指定初始容量就无需在向 Dictionary<TKey,TValue>中添加元素时执行大量大小调整操作。

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

此构造函数是 O (1) 操作。

另请参阅

适用于

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

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并使用指定的 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);
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))

参数

dictionary
IDictionary<TKey,TValue>

IDictionary<TKey,TValue>,它的元素被复制到新 Dictionary<TKey,TValue>

comparer
IEqualityComparer<TKey>

比较键时要使用的 IEqualityComparer<T> 实现,或者为 null,以便为键类型使用默认的 EqualityComparer<T>

例外

dictionary 上声明的默认值为 null

dictionary 包含一个或多个重复键。

示例

下面的代码示例演示如何使用 Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) 构造函数从另一个 Dictionary<TKey,TValue> 字典使用不区分大小写的排序内容初始化 。 该代码示例使用不区分大小写的比较器创建 SortedDictionary<TKey,TValue> ,并按随机顺序填充数据,然后将 传递给SortedDictionary<TKey,TValue>Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)构造函数,以及不区分大小写的相等比较器,从而创建Dictionary<TKey,TValue>排序的 。 如果需要生成在某个时间点变为静态的排序字典,这非常有用;将数据从 SortedDictionary<TKey,TValue> 复制到 可以提高 Dictionary<TKey,TValue> 检索速度。

注意

使用不区分大小写的比较器创建新字典并使用使用区分大小写的比较器的字典中的条目填充该字典时,如本示例所示,如果输入字典的键仅因大小写而异,则会发生异常。

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 不区分大小写的字符串比较器一起使用,以创建具有不区分大小写的字符串键的字典。

根据指定的比较器,中的每个键都必须是唯一 Dictionary<TKey,TValue> 的;同样,源 dictionary 中的每个键也必须根据指定的比较器是唯一的。

注意

例如,如果 comparer 是 类提供的 StringComparer 不区分大小写的字符串比较器之一,并且 dictionary 不使用不区分大小写的比较器键,则可能会出现重复键。

Dictionary<TKey,TValue> 的初始容量足以包含 中的所有 dictionary元素。

Dictionary<TKey,TValue> 需要相等实现来确定键是否相等。 如果 comparernull,则此构造函数使用默认的泛型相等比较器 EqualityComparer<T>.Default。 如果 类型 TKey 实现 System.IEquatable<T> 泛型接口,则默认相等比较器使用该实现。

此构造函数是 O (n) 操作,其中 n 是 中的 dictionary元素数。

另请参阅

适用于

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

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IEnumerable<T> 中复制的元素并使用指定的 IEqualityComparer<T>

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);
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>>

IEnumerable<T>,它的元素被复制到新 Dictionary<TKey,TValue>

comparer
IEqualityComparer<TKey>

比较键时要使用的 IEqualityComparer<T> 实现,或者为 null,以便为键类型使用默认的 EqualityComparer<T>

例外

collection 上声明的默认值为 null

collection 包含一个或多个重复的键。

适用于

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

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空,具有指定的初始容量并使用指定的 IEqualityComparer<T>

public:
 Dictionary(int capacity, System::Collections::Generic::IEqualityComparer<TKey> ^ comparer);
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

Dictionary<TKey,TValue> 可包含的初始元素数。

comparer
IEqualityComparer<TKey>

比较键时要使用的 IEqualityComparer<T> 实现,或者为 null,以便为键类型使用默认的 EqualityComparer<T>

例外

capacity 小于 0。

示例

下面的代码示例为当前区域性创建 Dictionary<TKey,TValue> 初始容量为 5 且不区分大小写的相等比较器。 该示例添加了四个元素,其中一些具有小写键,一些元素使用大写键。 然后,该示例尝试添加一个元素,该元素的键仅在大小写上与现有键不同,捕获生成的异常并显示错误消息。 最后,该示例显示字典中的元素。

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 不区分大小写的字符串比较器一起使用,以创建具有不区分大小写的字符串键的字典。

根据指定的比较器, Dictionary<TKey,TValue> 中的每个键都必须是唯一的。

Dictionary<TKey,TValue> 容量是在需要调整大小之前可以添加到 的 Dictionary<TKey,TValue> 元素数。 将元素添加到 时 Dictionary<TKey,TValue>,通过重新分配内部数组,容量会根据需要自动增加。

如果可以估计集合的大小,则指定初始容量就无需在向 Dictionary<TKey,TValue>中添加元素时执行大量大小调整操作。

Dictionary<TKey,TValue> 需要相等实现来确定键是否相等。 如果 comparernull,则此构造函数使用默认的泛型相等比较器 EqualityComparer<T>.Default。 如果 类型 TKey 实现 System.IEquatable<T> 泛型接口,则默认相等比较器使用该实现。

此构造函数是 O (1) 操作。

另请参阅

适用于

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

注意

This API supports obsolete formatter-based serialization. It should not be called or extended by application code.

用序列化数据初始化 Dictionary<TKey,TValue> 类的新实例。

protected:
 Dictionary(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected Dictionary (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
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>
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
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 对象包含序列化 Dictionary<TKey,TValue> 所需的信息。

context
StreamingContext

StreamingContext 结构,该结构包含与 Dictionary<TKey,TValue> 相关联的序列化流的源和目标。

属性

注解

在反序列化期间调用此构造函数,以重建通过流传输的对象。 有关详细信息,请参阅 XML 和 SOAP 序列化

另请参阅

适用于