OrderedDictionary.Add(Object, Object) 方法

定义

使用最小的可用索引,将具有指定键和值的项添加到 OrderedDictionary 集合中。

public:
 virtual void Add(System::Object ^ key, System::Object ^ value);
public void Add (object key, object value);
public void Add (object key, object? value);
abstract member Add : obj * obj -> unit
override this.Add : obj * obj -> unit
Public Sub Add (key As Object, value As Object)

参数

key
Object

要添加的条目的键。

value
Object

要添加的条目的值。 此值可为 null

实现

例外

OrderedDictionary 集合中已存在具有相同键的元素。

示例

下面的代码示例演示集合的 OrderedDictionary 创建和填充。 此代码是可在 中查看的较大代码示例的 OrderedDictionary一部分。

// Creates and initializes a OrderedDictionary.
OrderedDictionary^ myOrderedDictionary = gcnew OrderedDictionary();
myOrderedDictionary->Add("testKey1", "testValue1");
myOrderedDictionary->Add("testKey2", "testValue2");
myOrderedDictionary->Add("keyToDelete", "valueToDelete");
myOrderedDictionary->Add("testKey3", "testValue3");

ICollection^ keyCollection = myOrderedDictionary->Keys;
ICollection^ valueCollection = myOrderedDictionary->Values;

// Display the contents using the key and value collections
DisplayContents(keyCollection, valueCollection, myOrderedDictionary->Count);
// Creates and initializes a OrderedDictionary.
OrderedDictionary myOrderedDictionary = new OrderedDictionary();
myOrderedDictionary.Add("testKey1", "testValue1");
myOrderedDictionary.Add("testKey2", "testValue2");
myOrderedDictionary.Add("keyToDelete", "valueToDelete");
myOrderedDictionary.Add("testKey3", "testValue3");

ICollection keyCollection = myOrderedDictionary.Keys;
ICollection valueCollection = myOrderedDictionary.Values;

// Display the contents using the key and value collections
DisplayContents(keyCollection, valueCollection, myOrderedDictionary.Count);
' Creates and initializes a OrderedDictionary.
Dim myOrderedDictionary As New OrderedDictionary()
myOrderedDictionary.Add("testKey1", "testValue1")
myOrderedDictionary.Add("testKey2", "testValue2")
myOrderedDictionary.Add("keyToDelete", "valueToDelete")
myOrderedDictionary.Add("testKey3", "testValue3")

Dim keyCollection As ICollection = myOrderedDictionary.Keys
Dim valueCollection As ICollection = myOrderedDictionary.Values

' Display the contents Imports the key and value collections
DisplayContents( _
    keyCollection, valueCollection, myOrderedDictionary.Count)

注解

键不能是 null,但值可以是 。

还可以使用 Item[] 属性通过设置集合中 OrderedDictionary 不存在的键的值来添加新元素;但是,如果 指定的键已存在于 中 OrderedDictionary,则 Item[] 设置 属性将覆盖旧值。 相反, Add 方法不修改现有元素,而是引发 ArgumentException

适用于