簡體   English   中英

將一個字符串數組復制到另一個

[英]Copy one string array to another

我怎樣才能復制string[]從另一個string[]

假設我有string[] args 如何將其復制到另一個數組string[] args1

  • 要創建具有相同內容的全新數組(作為淺表副本):調用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" } 

為目標數組分配空間,使用Array.CopyTo():

targetArray = new string[sourceArray.Length];
sourceArray.CopyTo( targetArray, 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));
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM