2009-05-20 113 views

回答

17

分配空間爲目標磁盤陣列,使用Array.CopyTo():

targetArray = new string[sourceArray.Length]; 
sourceArray.CopyTo(targetArray, 0); 
+4

使用clone()對這種特殊情況下一個班輪雖然。 – 2009-05-20 07:23:02

27
  • 要創建具有相同內容的全新陣列(如淺表副本):呼叫Array.Clone和只投結果。
  • 爲字符串陣列的一部分複製到另一個字符串數組:呼叫Array.CopyArray.CopyTo

例如:

using System; 

class Test 
{ 
    static void Main(string[] args) 
    { 
     // Clone the whole array 
     string[] args2 = (string[]) args.Clone(); 

     // Copy the five elements with indexes 2-6 
     // from args into args3, stating from 
     // index 2 of args3. 
     string[] args3 = new string[5]; 
     Array.Copy(args, 2, args3, 0, 5); 

     // Copy whole of args into args4, starting from 
     // index 2 (of args4) 
     string[] args4 = new string[args.Length+2]; 
     args.CopyTo(args4, 2); 
    } 
} 

假設我們開始了與args = { "a", "b", "c", "d", "e", "f", "g", "h" }的結果是:

args2 = { "a", "b", "c", "d", "e", "f", "g", "h" } 
args3 = { "c", "d", "e", "f", "g" } 
args4 = { null, null, "a", "b", "c", "d", "e", "f", "g", "h" } 
+0

嗨,Jon,爲什麼字符串數組克隆'深'克隆?我的意思是我知道Array.Clone()是一個淺拷貝;雖然它在其他引用類型(例如CultureInfo)上做了一個淺拷貝,但它以某種方式在字符串數組上進行了「深層」拷貝。例如,如果我克隆一個包含「Hello」,「World」的數組;在克隆之後,我將第一個元素設置爲null。然後我期望克隆數組的第一個元素也應該是null,但它仍然是Hello。希望你知道我的意思而不能在評論中顯示代碼示例。 – stt106 2015-01-27 10:57:31

0

上面的答案顯示了一個淺層克隆;所以我想我使用序列化添加了一個深層克隆示例;當然也可以通過循環原始數組並將每個元素複製到一個全新的數組中來完成深度克隆。

private static T[] ArrayDeepCopy<T>(T[] source) 
     { 
      using (var ms = new MemoryStream()) 
      { 
       var bf = new BinaryFormatter{Context = new StreamingContext(StreamingContextStates.Clone)}; 
       bf.Serialize(ms, source); 
       ms.Position = 0; 
       return (T[]) bf.Deserialize(ms); 
      } 
     } 

測試深克隆:

private static void ArrayDeepCloneTest() 
     { 
      //a testing array 
      CultureInfo[] secTestArray = { new CultureInfo("en-US", false), new CultureInfo("fr-FR") }; 

      //deep clone 
      var secCloneArray = ArrayDeepCopy(secTestArray); 

      //print out the cloned array 
      Array.ForEach(secCloneArray, x => Console.WriteLine(x.DateTimeFormat.DateSeparator)); 

      //modify the original array 
      secTestArray[0].DateTimeFormat.DateSeparator = "-"; 

      Console.WriteLine(); 
      //show the (deep) cloned array unchanged whereas a shallow clone would reflect the change... 
      Array.ForEach(secCloneArray, x => Console.WriteLine(x.DateTimeFormat.DateSeparator)); 
     } 
相關問題