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. 這個範例會示範Add ArgumentException當嘗試加入重複的索引鍵時,方法會擲回。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. 如果comparernull,則此函式會使用EqualityComparer<T>.Default預設的泛型相等比較子。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. 如果comparernull,則此函式會使用EqualityComparer<T>.Default預設的泛型相等比較子。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 (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>>, 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. 如果comparernull,則此函式會使用EqualityComparer<T>.Default預設的泛型相等比較子。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.

另請參閱

適用於