在 C# 中将 Collection 元素复制到数组
csharpserver side programmingprogramming更新于 2025/10/7 3:02:00
要将 Collection 元素复制到数组,代码如下 −
示例
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main(){
Collection<string> col = new Collection<string>();
col.Add("One");
col.Add("Two");
col.Add("Three");
col.Add("Four");
col.Add("Five");
col.Add("Six");
col.Add("Seven");
col.Add("Eight");
Console.WriteLine("Collection....");
foreach(string str in col){
Console.WriteLine(str);
}
string[] strArr = new string[10];
col.CopyTo(strArr, 2);
Console.WriteLine("
Array...");
foreach(string str in strArr){
Console.WriteLine(str);
}
}
}
输出
这将产生以下输出 −
Collection.... One Two Three Four Five Six Seven Eight Array... One Two Three Four Five Six Seven Eight
示例
现在让我们看另一个例子 −
using System;
using System.Collections.ObjectModel;
public class Demo {
public static void Main(){
Collection<string> col = new Collection<string>();
col.Add("One");
col.Add("Two");
col.Add("Three");
col.Add("Four");
col.Add("Five");
Console.WriteLine("Collection....");
foreach(string str in col){
Console.WriteLine(str);
}
string[] strArr = new string[10];
col.CopyTo(strArr, 3);
Console.WriteLine("
Array...");
foreach(string str in strArr){
Console.WriteLine(str);
}
}
}
输出
这将产生以下输出 −
Collection.... One Two Three Four Five Array... One Two Three Four Five

