SortedDictionary<TKey,TValue>.Add(TKey, TValue) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將具有指定鍵與值的元素加入 SortedDictionary<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 參考型別。
實作
例外狀況
key 是 null。
具有相同鍵的元素已存在 SortedDictionary<TKey,TValue>於 中。
範例
以下程式碼範例建立一個包含字串鍵的空 SortedDictionary<TKey,TValue> 字串,並使用此 Add 方法加入一些元素。 範例顯示該Add方法在嘗試新增重複鍵時會拋出 。ArgumentException
此程式碼範例是本類別更大範例 SortedDictionary<TKey,TValue> 的一部分。
// Create a new sorted dictionary of strings, with string
// keys.
SortedDictionary<string, string> openWith =
new SortedDictionary<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 sorted dictionary of strings, with string
' keys.
Dim openWith As New SortedDictionary(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[] 特性,透過設定不存在 SortedDictionary<TKey,TValue>於 ;;的鍵值來新增元素;例如, myCollection["myNonexistentKey"] = myValue (在 Visual Basic 中, myCollection("myNonexistantKey") = myValue)。 然而,如果指定的鍵已經存在 SortedDictionary<TKey,TValue>於 中,設定屬性 Item[] 會覆蓋舊值。 相較之下,若已有具有指定鍵的元素存在,則 Add 該方法會拋出例外。
若值null類型是參考型態,鍵值不可能是 TValue,但值可以是。
此方法是一個 O(log n) 操作,其中 n 為 Count。