C# 中的克隆


如果你想要克隆一个数组,C# 中的克隆非常有用。C# 中的 Clone() 方法用于创建数组的一个类似副本。C# 具有 Clone 方法和 ICloneable 接口。

让我们看一个使用 Clone() 方法克隆数组的示例:

示例

 实时演示

using System;

class Program {
   static void Main() {
      string[] arr = { "one", "two", "three", "four", "five" };
      string[] arrCloned = arr.Clone() as string[];

      Console.WriteLine(string.Join(",", arr));
      Console.WriteLine(string.Join(",", arrCloned));
      Console.WriteLine();
   }
}

输出

one,two,three,four,five
one,two,three,four,five

上面,我们有一个字符串数组:

string[] arr = { "one", "two", "three", "four", "five" };

与此相对应,在一个新的字符串数组中,我们使用了带有“as”运算符的 Clone() 方法来复制数组:

string[] arrCloned = arr.Clone() as string[];

更新于: 20-6 月-2020

318 次浏览

提升您的 职业

通过完成该课程获得认证

开始
广告
© . All rights reserved.