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

定義

將有指定索引鍵和數值的項目加入 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

實作

例外狀況

keynull

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("myNonexistantKey") = myValue 例如, myCollection["myNonexistentKey"] = myValue 在 Visual Basic 中 (,) 。 不過,如果指定的索引鍵已存在於 中 SortedDictionary<TKey,TValue> ,則設定 Item[] 屬性會覆寫舊的值。 相反地, Add 如果具有指定索引鍵的專案已經存在,方法就會擲回例外狀況。

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

這個方法是 O (記錄 n) 作業,其中 nCount

適用於

另請參閱