Hashtable.Add(Object, Object) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將具有指定鍵與值的元素加入 Hashtable。
public:
virtual void Add(System::Object ^ key, System::Object ^ value);
public virtual void Add(object key, object value);
public virtual void Add(object key, object? value);
abstract member Add : obj * obj -> unit
override this.Add : obj * obj -> unit
Public Overridable Sub Add (key As Object, value As Object)
參數
- key
- Object
元素的關鍵是要添加的。
- value
- Object
要加入元素的價值。 其值可以是 null。
實作
例外狀況
key 是 null。
具有相同鍵的元素已存在 Hashtable於 中。
範例
以下範例說明如何將元素加入 Hashtable。
using System;
using System.Collections;
public class SamplesHashtable
{
public static void Main()
{
// Creates and initializes a new Hashtable.
var myHT = new Hashtable();
myHT.Add("one", "The");
myHT.Add("two", "quick");
myHT.Add("three", "brown");
myHT.Add("four", "fox");
// Displays the Hashtable.
Console.WriteLine("The Hashtable contains the following:");
PrintKeysAndValues(myHT);
}
public static void PrintKeysAndValues( Hashtable myHT )
{
Console.WriteLine("\t-KEY-\t-VALUE-");
foreach (DictionaryEntry de in myHT)
Console.WriteLine($"\t{de.Key}:\t{de.Value}");
Console.WriteLine();
}
}
/*
This code produces the following output.
The Hashtable contains the following:
-KEY- -VALUE-
two: quick
three: brown
four: fox
one: The
*/
Imports System.Collections
Public Class SamplesHashtable
Public Shared Sub Main()
' Creates and initializes a new Hashtable.
Dim myHT As New Hashtable()
myHT.Add("one", "The")
myHT.Add("two", "quick")
myHT.Add("three", "brown")
myHT.Add("four", "fox")
' Displays the Hashtable.
Console.WriteLine("The Hashtable contains the following:")
PrintKeysAndValues(myHT)
End Sub
Public Shared Sub PrintKeysAndValues(myHT As Hashtable)
Console.WriteLine(vbTab + "-KEY-" + vbTab + "-VALUE-")
For Each de As DictionaryEntry In myHT
Console.WriteLine(vbTab + "{0}:" + vbTab + "{1}", de.Key, de.Value)
Next
Console.WriteLine()
End Sub
End Class
' This code produces the following output.
'
' The Hashtable contains the following:
' -KEY- -VALUE-
' two: quick
' one: The
' three: brown
' four: fox
'
備註
索引鍵不能 null,但值可以是 。
一個狀態與雜湊碼值之間沒有關聯的物件,通常不應該被用作鍵。 例如,String 物件比 StringBuilder 物件更適合用作鍵。
你也可以利用這個 Item[] 屬性來新增元素,方法是設定不存在 Hashtable於 中的鍵值;例如, myCollection["myNonexistentKey"] = myValue。 然而,如果指定的鍵已經存在 Hashtable於 中,設定屬性 Item[] 會覆蓋舊值。 相較之下,該 Add 方法不會修改現有元素。
若 Count 小於 的容量 Hashtable,此方法即為 O(1) 運算。 若需增加容量以容納新元素,此方法即為 O(n) 運算,其中 n 為 Count。