用于克隆或复制列表的 C# 程序

来源:这里教程网 时间:2026-02-21 16:20:57 作者:

用于克隆或复制列表的 c# 程序

要复制或克隆 C# 列表,请首先设置一个列表。

List < string > myList = new List < string > ();
myList.Add("One");
myList.Add("Two");

现在声明一个字符串数组并使用 CopyTo() 方法进行复制。

string[] arr = new string[10];
myList.CopyTo(arr);

让我们看看将列表复制到一维数组的完整代码。

示例

using System;
using System.Collections.Generic;
using System.Linq;
public class Demo {
   public static void Main() {
      List < string > myList = new List < string > ();
      myList.Add("One");
      myList.Add("Two");
      myList.Add("Three");
      myList.Add("Four");
      Console.WriteLine("First list...");
      foreach(string value in list1) {
         Console.WriteLine(value);
      }
      string[] arr = new string[20];
      myList.CopyTo(arr);
      Console.WriteLine("After copy...");
      foreach(string value in arr) {
         Console.WriteLine(value);
      }
   }
}

相关推荐