Copy one string array to another

前端 未结 3 579
遇见更好的自我
遇见更好的自我 2020-12-30 01:13

How can I copy a string[] from another string[]?

Suppose I have string[] args. How can I copy it to another array string

3条回答
  •  不思量自难忘°
    2020-12-30 02:16

    The above answers show a shallow clone; so I thought I add a deep clone example using serialization; of course a deep clone can also be done by looping through the original array and copy each element into a brand new array.

     private static T[] ArrayDeepCopy(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);
                }
            }
    

    Testing the deep clone:

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

提交回复
热议问题