Dictionary<TKey,TValue> Konstruktory
Definicja
Ważne
Niektóre informacje odnoszą się do produktu w wersji wstępnej, który może zostać znacząco zmodyfikowany przed wydaniem. Firma Microsoft nie udziela żadnych gwarancji, jawnych lub domniemanych, w odniesieniu do informacji podanych w tym miejscu.
Inicjuje nowe wystąpienie klasy Dictionary<TKey,TValue>.
Przeciążenia
| Nazwa | Opis |
|---|---|
| Dictionary<TKey,TValue>() |
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy, która jest pusta, ma domyślną pojemność początkową i używa domyślnego porównania równości dla typu klucza. |
| Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) |
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy zawierające elementy skopiowane z określonej IDictionary<TKey,TValue> klasy i używa domyślnego porównania równości dla typu klucza. |
| Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) |
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy zawierające elementy skopiowane z określonego IEnumerable<T>elementu . |
| Dictionary<TKey,TValue>(IEqualityComparer<TKey>) |
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy, która jest pusta, ma domyślną pojemność początkową i używa określonego IEqualityComparer<T>elementu . |
| Dictionary<TKey,TValue>(Int32) |
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy, która jest pusta, ma określoną pojemność początkową i używa domyślnego porównania równości dla typu klucza. |
| Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) |
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy zawierające elementy skopiowane z określonego IDictionary<TKey,TValue> elementu i używa określonego IEqualityComparer<T>elementu . |
| Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) |
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy zawierające elementy skopiowane z określonego IEnumerable<T> elementu i używa określonego IEqualityComparer<T>elementu . |
| Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) |
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy, która jest pusta, ma określoną pojemność początkową i używa określonego IEqualityComparer<T>elementu . |
| Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) |
Przestarzałe.
Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy z serializowanymi danymi. |
Dictionary<TKey,TValue>()
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy, która jest pusta, ma domyślną pojemność początkową i używa domyślnego porównania równości dla typu klucza.
public:
Dictionary();
public Dictionary();
Public Sub New ()
Przykłady
Poniższy przykład kodu tworzy puste Dictionary<TKey,TValue> ciągi z kluczami ciągów i używa Add metody w celu dodania niektórych elementów. W przykładzie Add pokazano, że metoda zgłasza ArgumentException błąd podczas próby dodania zduplikowanego klucza.
Ten przykład kodu jest częścią większego przykładu udostępnionego dla klasy Dictionary<TKey,TValue>.
// 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
Uwagi
Każdy klucz w obiekcie Dictionary<TKey,TValue> musi być unikatowy zgodnie z domyślnym modułem porównywania równości.
Dictionary<TKey,TValue> wymaga implementacji równości, aby określić, czy klucze są równe. Ten konstruktor używa domyślnego porównania równości ogólnej, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji. Alternatywnie można określić implementację interfejsu IEqualityComparer<T> ogólnego przy użyciu konstruktora, który akceptuje comparer parametr.
Note
Jeśli możesz oszacować rozmiar kolekcji, używając konstruktora, który określa początkową pojemność eliminuje konieczność wykonania wielu operacji zmiany rozmiaru podczas dodawania elementów do elementu Dictionary<TKey,TValue>.
Ten konstruktor jest operacją O(1).
Zobacz też
Dotyczy
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>)
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy zawierające elementy skopiowane z określonej IDictionary<TKey,TValue> klasy i używa domyślnego porównania równości dla typu klucza.
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))
Parametry
- dictionary
- IDictionary<TKey,TValue>
Element IDictionary<TKey,TValue> , którego elementy są kopiowane do nowego Dictionary<TKey,TValue>elementu .
Wyjątki
Parametr dictionary ma wartość null.
dictionary zawiera co najmniej jeden zduplikowany klucz.
Przykłady
W poniższym przykładzie kodu pokazano, jak za pomocą konstruktora Dictionary<TKey,TValue>(IEqualityComparer<TKey>) zainicjować Dictionary<TKey,TValue> element z posortowaną zawartością z innego słownika. Przykładowy kod tworzy SortedDictionary<TKey,TValue> obiekt i wypełnia je danymi w kolejności losowej, a następnie przekazuje SortedDictionary<TKey,TValue> element do Dictionary<TKey,TValue>(IEqualityComparer<TKey>) konstruktora, tworząc Dictionary<TKey,TValue> posortowany obiekt. Jest to przydatne, jeśli musisz utworzyć posortowany słownik, który w pewnym momencie staje się statyczny; kopiowanie danych z elementu do SortedDictionary<TKey,TValue> elementu Dictionary<TKey,TValue> zwiększa szybkość pobierania.
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
*/
open System.Collections.Generic
// Create a new sorted dictionary of strings, with string
// keys.
let openWith = 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.
let copy = Dictionary<string, string> openWith
// List the contents of the copy.
printfn ""
for kvp in copy do
printfn $"Key = {kvp.Key}, Value = {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
Uwagi
Każdy klucz w elemecie Dictionary<TKey,TValue> musi być unikatowy zgodnie z domyślnym modułem porównywania równości; podobnie każdy klucz w źródle dictionary musi być również unikatowy zgodnie z domyślnym modułem porównywania równości.
Początkowa pojemność nowego Dictionary<TKey,TValue> jest wystarczająco duża, aby zawierała wszystkie elementy w pliku dictionary.
Dictionary<TKey,TValue> wymaga implementacji równości, aby określić, czy klucze są równe. Ten konstruktor używa domyślnego porównania równości ogólnej, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji. Alternatywnie można określić implementację interfejsu IEqualityComparer<T> ogólnego przy użyciu konstruktora, który akceptuje comparer parametr.
Ten konstruktor jest operacją O(n), gdzie n jest liczbą elementów w .dictionary
Zobacz też
Dotyczy
Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy zawierające elementy skopiowane z określonego IEnumerable<T>elementu .
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)))
Parametry
- collection
- IEnumerable<KeyValuePair<TKey,TValue>>
Element IEnumerable<T> , którego elementy są kopiowane do nowego Dictionary<TKey,TValue>elementu .
Wyjątki
Parametr collection ma wartość null.
collection zawiera co najmniej jeden zduplikowany klucz.
Dotyczy
Dictionary<TKey,TValue>(IEqualityComparer<TKey>)
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy, która jest pusta, ma domyślną pojemność początkową i używa określonego IEqualityComparer<T>elementu .
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))
Parametry
- comparer
- IEqualityComparer<TKey>
Implementacja IEqualityComparer<T> używana podczas porównywania kluczy lub null używania wartości domyślnej EqualityComparer<T> dla typu klucza.
Przykłady
Poniższy przykład kodu tworzy element Dictionary<TKey,TValue> z porównaniem równości bez uwzględniania wielkości liter dla bieżącej kultury. W przykładzie dodano cztery elementy, niektóre z małymi literami i niektóre z wielkimi literami. W tym przykładzie podjęto próbę dodania elementu z kluczem, który różni się od istniejącego klucza tylko według wielkości liter, przechwytuje wynikowy wyjątek i wyświetla komunikat o błędzie. Na koniec przykład wyświetla elementy w słowniku.
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
*/
open System
open System.Collections.Generic
// Create a new Dictionary of strings, with string keys
// and a case-insensitive comparer for the current culture.
let openWith = 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")
with :? ArgumentException ->
printfn "\nBMP is already in the dictionary."
// List the contents of the sorted dictionary.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {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
Uwagi
Użyj tego konstruktora z modułami porównującymi ciągi bez uwzględniania wielkości liter dostarczone przez klasę StringComparer , aby utworzyć słowniki z kluczami ciągów bez uwzględniania wielkości liter.
Każdy klucz w obiekcie Dictionary<TKey,TValue> musi być unikatowy zgodnie z określonym modułem porównującym.
Dictionary<TKey,TValue> wymaga implementacji równości, aby określić, czy klucze są równe. Jeśli comparer ma nullwartość , ten konstruktor używa domyślnego ogólnego porównania równości, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji.
Note
Jeśli możesz oszacować rozmiar kolekcji, używając konstruktora, który określa początkową pojemność eliminuje konieczność wykonania wielu operacji zmiany rozmiaru podczas dodawania elementów do elementu Dictionary<TKey,TValue>.
Ten konstruktor jest operacją O(1).
Caution
Jeśli capacity pochodzi z danych wejściowych użytkownika, preferuj użycie konstruktora bez parametru pojemności i umożliwienie zmiany rozmiaru kolekcji w miarę dodawania elementów. Jeśli musisz użyć wartości określonej przez użytkownika, zaciśnięć ją do rozsądnego limitu (na przykład ) lub sprawdzić, Math.Clamp(untrustedValue, 0, 20)czy liczba elementów jest zgodna z określoną wartością.
Zobacz też
Dotyczy
Dictionary<TKey,TValue>(Int32)
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy, która jest pusta, ma określoną pojemność początkową i używa domyślnego porównania równości dla typu klucza.
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)
Parametry
- capacity
- Int32
Początkowa liczba elementów, które Dictionary<TKey,TValue> mogą zawierać.
Wyjątki
capacity wartość jest mniejsza niż 0.
Przykłady
Poniższy przykład kodu tworzy słownik z początkową pojemnością 4 i wypełnia go 4 wpisami.
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
*/
open System.Collections.Generic
// Create a new dictionary of strings, with string keys and
// an initial capacity of 4.
let openWith = 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.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {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
Uwagi
Każdy klucz w obiekcie Dictionary<TKey,TValue> musi być unikatowy zgodnie z domyślnym modułem porównywania równości.
Pojemność elementu Dictionary<TKey,TValue> to liczba elementów, które można dodać do elementu przed zmianą rozmiaru Dictionary<TKey,TValue> jest konieczna. W miarę dodawania Dictionary<TKey,TValue>elementów do obiektu pojemność jest automatycznie zwiększana zgodnie z wymaganiami przez przydzielenie tablicy wewnętrznej.
Jeśli można oszacować rozmiar kolekcji, określenie początkowej pojemności eliminuje konieczność wykonania wielu operacji zmiany rozmiaru podczas dodawania elementów do elementu Dictionary<TKey,TValue>.
Dictionary<TKey,TValue> wymaga implementacji równości, aby określić, czy klucze są równe. Ten konstruktor używa domyślnego porównania równości ogólnej, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji. Alternatywnie można określić implementację interfejsu IEqualityComparer<T> ogólnego przy użyciu konstruktora, który akceptuje comparer parametr.
Ten konstruktor jest operacją O(1).
Caution
Jeśli capacity pochodzi z danych wejściowych użytkownika, preferuj użycie konstruktora bez parametru pojemności i umożliwienie zmiany rozmiaru kolekcji w miarę dodawania elementów. Jeśli musisz użyć wartości określonej przez użytkownika, zaciśnięć ją do rozsądnego limitu (na przykład ) lub sprawdzić, Math.Clamp(untrustedValue, 0, 20)czy liczba elementów jest zgodna z określoną wartością.
Zobacz też
Dotyczy
Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy zawierające elementy skopiowane z określonego IDictionary<TKey,TValue> elementu i używa określonego IEqualityComparer<T>elementu .
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))
Parametry
- dictionary
- IDictionary<TKey,TValue>
Element IDictionary<TKey,TValue> , którego elementy są kopiowane do nowego Dictionary<TKey,TValue>elementu .
- comparer
- IEqualityComparer<TKey>
Implementacja IEqualityComparer<T> używana podczas porównywania kluczy lub null używania wartości domyślnej EqualityComparer<T> dla typu klucza.
Wyjątki
Parametr dictionary ma wartość null.
dictionary zawiera co najmniej jeden zduplikowany klucz.
Przykłady
W poniższym przykładzie kodu pokazano, jak za pomocą konstruktora Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) zainicjować zawartość Dictionary<TKey,TValue> posortowaną bez uwzględniania wielkości liter z innego słownika. Przykładowy kod tworzy SortedDictionary<TKey,TValue> obiekt z porównaniem bez uwzględniania wielkości liter i wypełnia je danymi w kolejności losowej, a następnie przekazuje SortedDictionary<TKey,TValue> element do Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) konstruktora wraz z porównującym równości bez uwzględniania wielkości liter, tworząc Dictionary<TKey,TValue> posortowany obiekt. Jest to przydatne, jeśli musisz utworzyć posortowany słownik, który w pewnym momencie staje się statyczny; kopiowanie danych z elementu do SortedDictionary<TKey,TValue> elementu Dictionary<TKey,TValue> zwiększa szybkość pobierania.
Note
Podczas tworzenia nowego słownika z modułem porównującym bez uwzględniania wielkości liter i wypełniania go wpisami ze słownika używającego porównania z uwzględnieniem wielkości liter, tak jak w tym przykładzie, występuje wyjątek, jeśli słownik wejściowy zawiera klucze, które różnią się tylko wielkością liter.
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
*/
open System
open System.Collections.Generic
// Create a new sorted dictionary of strings, with string
// keys and a case-insensitive comparer.
let openWith =
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.
let copy =
Dictionary<string, string>(openWith, StringComparer.CurrentCultureIgnoreCase)
// List the contents of the copy.
printfn ""
for kvp in copy do
printfn $"Key = {kvp.Key}, Value = {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
Uwagi
Użyj tego konstruktora z modułami porównującymi ciągi bez uwzględniania wielkości liter dostarczone przez klasę StringComparer , aby utworzyć słowniki z kluczami ciągów bez uwzględniania wielkości liter.
Każdy klucz w elemecie Dictionary<TKey,TValue> musi być unikatowy zgodnie z określonym modułem porównującym; podobnie każdy klucz w źródle dictionary musi być również unikatowy zgodnie z określonym modułem porównującym.
Note
Na przykład zduplikowane klucze mogą wystąpić, jeśli comparer jest jednym z porównań ciągów bez uwzględniania wielkości liter dostarczonych przez StringComparer klasę i dictionary nie używa klucza porównującego bez uwzględniania wielkości liter.
Początkowa pojemność nowego Dictionary<TKey,TValue> jest wystarczająco duża, aby zawierała wszystkie elementy w pliku dictionary.
Dictionary<TKey,TValue> wymaga implementacji równości, aby określić, czy klucze są równe. Jeśli comparer ma nullwartość , ten konstruktor używa domyślnego ogólnego porównania równości, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji.
Ten konstruktor jest operacją O(n), gdzie n jest liczbą elementów w .dictionary
Zobacz też
Dotyczy
Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy zawierające elementy skopiowane z określonego IEnumerable<T> elementu i używa określonego IEqualityComparer<T>elementu .
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))
Parametry
- collection
- IEnumerable<KeyValuePair<TKey,TValue>>
Element IEnumerable<T> , którego elementy są kopiowane do nowego Dictionary<TKey,TValue>elementu .
- comparer
- IEqualityComparer<TKey>
Implementacja IEqualityComparer<T> używana podczas porównywania kluczy lub null używania wartości domyślnej EqualityComparer<T> dla typu klucza.
Wyjątki
Parametr collection ma wartość null.
collection zawiera co najmniej jeden zduplikowany klucz.
Dotyczy
Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
Inicjuje nowe wystąpienie Dictionary<TKey,TValue> klasy, która jest pusta, ma określoną pojemność początkową i używa określonego IEqualityComparer<T>elementu .
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))
Parametry
- capacity
- Int32
Początkowa liczba elementów, które Dictionary<TKey,TValue> mogą zawierać.
- comparer
- IEqualityComparer<TKey>
Implementacja IEqualityComparer<T> używana podczas porównywania kluczy lub null używania wartości domyślnej EqualityComparer<T> dla typu klucza.
Wyjątki
capacity wartość jest mniejsza niż 0.
Przykłady
Poniższy przykład kodu tworzy Dictionary<TKey,TValue> obiekt z początkową pojemnością 5 i porównującym równość bez uwzględniania wielkości liter dla bieżącej kultury. W przykładzie dodano cztery elementy, niektóre z małymi literami i niektóre z wielkimi literami. W tym przykładzie podjęto próbę dodania elementu z kluczem, który różni się od istniejącego klucza tylko według wielkości liter, przechwytuje wynikowy wyjątek i wyświetla komunikat o błędzie. Na koniec przykład wyświetla elementy w słowniku.
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
*/
open System
open System.Collections.Generic
// Create a new dictionary of strings, with string keys, an
// initial capacity of 5, and a case-insensitive equality
// comparer.
let openWith =
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")
with :? ArgumentException ->
printfn "\nBMP is already in the dictionary."
// List the contents of the dictionary.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {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
Uwagi
Użyj tego konstruktora z modułami porównującymi ciągi bez uwzględniania wielkości liter dostarczone przez klasę StringComparer , aby utworzyć słowniki z kluczami ciągów bez uwzględniania wielkości liter.
Każdy klucz w obiekcie Dictionary<TKey,TValue> musi być unikatowy zgodnie z określonym modułem porównującym.
Pojemność elementu Dictionary<TKey,TValue> to liczba elementów, które można dodać do elementu przed zmianą rozmiaru Dictionary<TKey,TValue> jest konieczna. W miarę dodawania Dictionary<TKey,TValue>elementów do obiektu pojemność jest automatycznie zwiększana zgodnie z wymaganiami przez przydzielenie tablicy wewnętrznej.
Jeśli można oszacować rozmiar kolekcji, określenie początkowej pojemności eliminuje konieczność wykonania wielu operacji zmiany rozmiaru podczas dodawania elementów do elementu Dictionary<TKey,TValue>.
Dictionary<TKey,TValue> wymaga implementacji równości, aby określić, czy klucze są równe. Jeśli comparer ma nullwartość , ten konstruktor używa domyślnego ogólnego porównania równości, EqualityComparer<T>.Default. Jeśli typ TKey implementuje interfejs ogólny, domyślny moduł porównujący System.IEquatable<T> równości używa tej implementacji.
Ten konstruktor jest operacją O(1).
Zobacz też
Dotyczy
Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
- Źródło:
- Dictionary.cs
Uwaga
This API supports obsolete formatter-based serialization. It should not be called or extended by application code.
Inicjuje Dictionary<TKey,TValue> nowe wystąpienie klasy z serializowanymi danymi.
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);
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}")>]
new System.Collections.Generic.Dictionary<'Key, 'Value> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.Dictionary<'Key, 'Value>
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)
Parametry
- info
- SerializationInfo
SerializationInfo Obiekt zawierający informacje wymagane do serializacji obiektu Dictionary<TKey,TValue>.
- context
- StreamingContext
Struktura StreamingContext zawierająca źródło i miejsce docelowe serializowanego strumienia skojarzonego z elementem Dictionary<TKey,TValue>.
- Atrybuty
Uwagi
Ten konstruktor jest wywoływany podczas deserializacji w celu ponownego utworzenia obiektu przesyłanego przez strumień. Aby uzyskać więcej informacji, zobacz XML i SOAP Serialization.