IDictionary<TKey,TValue>.Add(TKey, TValue) Метод

Определение

Добавляет элемент с указанными ключом и значением в объект IDictionary<TKey,TValue>.

public:
 void Add(TKey key, TValue value);
public void Add (TKey key, TValue value);
abstract member Add : 'Key * 'Value -> unit
Public Sub Add (key As TKey, value As TValue)

Параметры

key
TKey

Объект, используемый в качестве ключа добавляемого элемента.

value
TValue

Объект, используемый в качестве значения добавляемого элемента.

Исключения

key имеет значение null.

Элемент с таким ключом уже существует в IDictionary<TKey,TValue>.

Объект IDictionary<TKey,TValue> доступен только для чтения.

Примеры

В следующем примере кода создается пустая Dictionary<TKey,TValue> строка с целыми ключами и обращается к ней через IDictionary<TKey,TValue> интерфейс. В примере кода используется Add метод для добавления некоторых элементов. В примере показано, что Add метод создает ArgumentException исключение при попытке добавить повторяющийся ключ.

Этот код является частью более крупного примера, который можно скомпилировать и выполнить. См. раздел System.Collections.Generic.IDictionary<TKey,TValue>.

// Create a new dictionary of strings, with string keys,
// and access it through the IDictionary generic interface.
IDictionary<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,
// and access it through the IDictionary generic interface.
IDictionary<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, 
' and access it through the IDictionary generic interface.
Dim openWith As IDictionary(Of String, String) = _
    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

Комментарии

Можно также использовать Item[] свойство для добавления новых элементов, задав значение ключа, который не существует в словаре; например, myCollection["myNonexistentKey"] = myValue в C# (myCollection("myNonexistentKey") = myValueв Visual Basic). Однако если указанный ключ уже существует в словаре, установка Item[] свойства перезаписывает старое значение. Напротив, Add метод не изменяет существующие элементы.

Реализации могут различаться в том, как они определяют равенство объектов; Например, List<T> класс использует Comparer<T>.Default, в то время как Dictionary<TKey,TValue> класс позволяет пользователю указать IComparer<T> реализацию для сравнения ключей.

Реализации могут различаться в том, разрешено key ли им быть null.

Применяется к

См. также раздел