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 次瀏覽

提升您的 職業

透過完成該課程獲得認證

開始
廣告