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-6-2020

634 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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