OrderedDictionary.CopyTo(Array,Int32)方法用于将OrderedDictionary元素复制到指定索引处的一维Array对象。
句法:
public void CopyTo (Array array, int index);
参数:
array: It is the one-dimensional Array which is the destination of the DictionaryEntry objects copied from OrderedDictionary. The Array must have zero-based indexing.
index: it is the zero-based index in array at which copying begins.
注意: OrderedDictionary.CopyTo(Array,Int32)方法不提供任何保证来维持OrderedDictionary集合中元素的顺序。
下面的程序说明了上述方法的用法:
范例1:
// C# code to copy OrderedDictionary to
// Array instance at the specified index
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver code
public static void Main()
{
// Creating a orderedDictionary named myDict
OrderedDictionary myDict = new OrderedDictionary();
// Adding key and value in myDict
myDict.Add("key1", "value1");
myDict.Add("key2", "value2");
myDict.Add("key3", "value3");
myDict.Add("key4", "value4");
myDict.Add("key5", "value5");
DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count];
// Copying OrderedDictionary to Array
// instance at the specified index
myDict.CopyTo(myArr, 0);
// Displaying elements in myArr
for (int i = 0; i < myArr.Length; i++) {
Console.WriteLine(myArr[i].Key + "-->"
+ myArr[i].Value);
}
}
}
输出:
key3-->value3
key4-->value4
key5-->value5
key2-->value2
key1-->value1
范例2:
// C# code to copy OrderedDictionary to
// Array instance at the specified index
// that give ArgumentOutOfRangeException
// due to the negative index
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver code
public static void Main()
{
// Creating a orderedDictionary named myDict
OrderedDictionary myDict = new OrderedDictionary();
// Adding key and value in myDict
myDict.Add("C", "1");
myDict.Add("C++", "2");
myDict.Add("Java", "3");
myDict.Add("C#", "4");
DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count];
// Copying OrderedDictionary to Array
// instance at the specified index
// This will raise "ArgumentOutOfRangeException"
// as index is less than 0
myDict.CopyTo(myArr, -2);
// Displaying elements in myArr
for (int i = 0; i < myArr.Length; i++) {
Console.WriteLine(myArr[i].Key + "-->"
+ myArr[i].Value);
}
}
}
运行时错误:
Unhandled Exception:
System.ArgumentOutOfRangeException: Non-negative number required.
Parameter name: arrayIndex
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.ordereddictionary.copyto?view=netframework-4.7.2