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

适用于

另请参阅