Dictionary<TKey,TValue>.Add(TKey, TValue) 方法

定義

將指定的索引鍵和值加入字典。

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

參數

key
TKey

要加入的項目的索引鍵。

value
TValue

要加入的項目的值。 參考類型的值可以是 null

實作

例外狀況

keynull

Dictionary<TKey,TValue> 中已存在具有相同索引鍵的元素。

範例

下列程式代碼範例會使用字串索引鍵建立空 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

備註

您也可以使用 Item[] 屬性來新增元素,方法是設定不存在於 中的 Dictionary<TKey,TValue>索引鍵值;例如, myCollection[myKey] = myValue 在 Visual Basic 中 (, myCollection(myKey) = myValue) 。 不過,如果指定的索引鍵已存在於 中 Dictionary<TKey,TValue>,則設定 Item[] 屬性會覆寫舊值。 相反地, Add 如果具有指定索引鍵的值已經存在,方法就會擲回例外狀況。

Count如果屬性值已經等於容量,則會藉由自動重新配置內部數位來增加的Dictionary<TKey,TValue>容量,而現有的元素會在新增專案之前複製到新的數位。

如果 參考型別,索引鍵不能是 nullTValue 但值可以是 。

如果 Count 小於容量,此方法會接近 O (1) 作業。 如果必須增加容量以容納新元素,這個方法會變成 O (n) 作業,其中 nCount

適用於

另請參閱