SortedList<TKey,TValue>.Add(TKey, TValue) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将带有指定键和值的元素添加到 SortedList<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
。
实现
例外
key
上声明的默认值为 null
。
SortedList<TKey,TValue> 中已存在具有相同键的元素。
示例
下面的代码示例使用字符串键创建一个空 SortedList<TKey,TValue> 字符串,并使用 Add 该方法添加一些元素。 该示例演示如何在 Add 尝试添加重复键时引发 ArgumentException 该方法。
此代码示例是为类提供的大型示例的 SortedList<TKey,TValue> 一部分。
// Create a new sorted list of strings, with string
// keys.
SortedList<String^, String^>^ openWith =
gcnew SortedList<String^, String^>();
// Add some elements to the list. 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 list.
try
{
openWith->Add("txt", "winword.exe");
}
catch (ArgumentException^)
{
Console::WriteLine("An element with Key = \"txt\" already exists.");
}
// Create a new sorted list of strings, with string
// keys.
SortedList<string, string> openWith =
new SortedList<string, string>();
// Add some elements to the list. 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 list.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
' Create a new sorted list of strings, with string
' keys.
Dim openWith As New SortedList(Of String, String)
' Add some elements to the list. 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 list.
Try
openWith.Add("txt", "winword.exe")
Catch
Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
注解
键不能 null
,但值可以是(如果排序列表中的 TValue
值类型)是引用类型。
还可以通过设置不存在的SortedList<TKey,TValue>键的值来使用该Item[]属性添加新元素,例如myCollection["myNonexistentKey"] = myValue
。 但是,如果指定的键已存在于该属性中 SortedList<TKey,TValue>,设置该 Item[] 属性将覆盖旧值。 相反,该方法 Add 不会修改现有元素。
如果 Count 已相等 Capacity,则通过自动重新分配内部数组来增加容量 SortedList<TKey,TValue> ,在添加新元素之前,现有元素将复制到新数组。
此方法是未排序数据的 O (n
) 操作,其中n
。Count 如果在列表末尾添加了新元素,则它是 O (日志 n
) 操作。 如果插入导致调整大小,则操作为 O () n
。