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

要用作要添加的元素的值的对象。

例外

keynull

中已存在具有相同键的 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>实现。

实现因是否允许keynull实现而异。

适用于

另请参阅