語言

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>於 中。

範例

以下程式碼範例會建立一個包含整數鍵的字串空 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 =
    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[] 屬性來新增元素,方法是設定字典中不存在的鍵值;例如,C# 中的 myCollection["myNonexistentKey"] = myValue(Visual Basic 中的 myCollection("myNonexistentKey") = myValue)。 然而,如果指定的鍵已經存在於字典中,設定該 Item[] 屬性會覆蓋舊值。 相較之下,該 Add 方法不會修改現有元素。

實作方式在決定物件相等的方式上可能有所不同;例如,類別 List<T> 使用 Comparer<T>.Default,而類別 Dictionary<TKey,TValue> 則允許使用者指定 IComparer<T> 用於比較鍵的實作。

實作方式可能有所不同,是否允許 key 。null

適用於

另請參閱