ListDictionary.CopyTo(Array,Int32)方法用于将ListDictionary条目复制到指定索引处的一维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 ListDictionary. The Array must have zero-based indexing.
index : The zero-based index in array at which copying begins.
例外情况:
- ArgumentNullException:如果数组为null。
- ArgumentOutOfRangeException:如果索引小于零。
- InvalidCastException:如果无法将源ListDictionary的类型强制转换为目标数组的类型。
- ArgumentException:如果数组是多维数组,或者源ListDictionary中的元素数大于从索引到目标数组末尾的可用空间。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# code to copy ListDictionary 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 ListDictionary named myDict
ListDictionary myDict = new ListDictionary();
myDict.Add("Australia", "Canberra");
myDict.Add("Belgium", "Brussels");
myDict.Add("Netherlands", "Amsterdam");
myDict.Add("China", "Beijing");
myDict.Add("Russia", "Moscow");
myDict.Add("India", "New Delhi");
DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count];
// Copying ListDictionary 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);
}
}
}
输出:
Australia-->Canberra
Belgium-->Brussels
Netherlands-->Amsterdam
China-->Beijing
Russia-->Moscow
India-->New Delhi
范例2:
// C# code to copy ListDictionary 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 ListDictionary named myDict
ListDictionary myDict = new ListDictionary();
myDict.Add("Australia", "Canberra");
myDict.Add("Belgium", "Brussels");
myDict.Add("Netherlands", "Amsterdam");
myDict.Add("China", "Beijing");
myDict.Add("Russia", "Moscow");
myDict.Add("India", "New Delhi");
DictionaryEntry[] myArr = new DictionaryEntry[myDict.Count];
// Copying ListDictionary to Array
// instance at the specified index
// This should 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: Index is less than zero.
Parameter name: index
笔记:
- 将元素以枚举器遍历ListDictionary的顺序复制到Array中。
- 要仅复制ListDictionary中的键,请使用ListDictionary.Keys.CopyTo 。
- 要仅复制ListDictionary中的值,请使用ListDictionary.Values.CopyTo 。
- 此方法是O(n)运算,其中n是Count。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.listdictionary.copyto?view=netframework-4.7.2