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" };

另外,在一個新的字串陣列中,我們使用了 Clone() 方法和“as”運算子來複制陣列 −

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

更新於: 20-6-2020

320 次瀏覽

開啟您的職業生涯

透過完成教程獲得認證

開始學習
廣告