C# 中的 Clone() 方法


C# 中的 Clone() 方法用於建立陣列的相似副本。

讓我們看一個使用 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));
      // cloned array
      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-Jun-2020

634 次瀏覽

開啟你的 職業生涯

透過完成課程取得認證

開始學習
廣告
© . All rights reserved.