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

定义

IDictionary<TKey,TValue> 添加一个带有所提供的键和值的元素。

C#
public void Add (TKey key, TValue value);

参数

key
TKey

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

value
TValue

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

例外

keynull

IDictionary<TKey,TValue> 中已存在具有相同键的元素。

示例

下面的代码示例使用整数键创建一个空 Dictionary<TKey,TValue> 字符串,并通过 IDictionary<TKey,TValue> 接口访问它。 代码示例使用 Add 方法添加一些元素。 该示例演示方法在 Add 尝试添加重复键时引发 ArgumentException

此代码是可以编译和执行的更大示例的一部分。 请参阅 System.Collections.Generic.IDictionary<TKey,TValue>

C#
// 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.");
}

注解

还可以使用 Item[] 属性通过设置字典中不存在的键的值来添加新元素;例如, myCollection["myNonexistentKey"] = myValue 在 C# (myCollection("myNonexistentKey") = myValue Visual Basic) 。 但是,如果字典中已存在指定的键,则设置 Item[] 属性将覆盖旧值。 相反, Add 方法不修改现有元素。

实现在确定对象相等性的方式上可能会有所不同;例如, List<T> 类使用 Comparer<T>.Default,而 Dictionary<TKey,TValue> 类允许用户指定 IComparer<T> 用于比较键的实现。

实现在是否允许 keynull方面可能会有所不同。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另请参阅