我该如何从另一个string[]
复制string[]
?
假设我有string[] args
。我该如何将它复制到另一个数组string[] args1
中?
Array.Clone
并将结果强制转换。Array.Copy
或 Array.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));
}
array[0] = null
,那就是在说“忽略数组中的旧值;新值为null”。为什么会影响其他数组呢?想象一下,我有一张打印出来的网址列表,并将其复印给你。如果我涂掉其中一个网址,这并不会对你的复印件产生任何影响。但是,如果我修改了其中一个网址所指向的页面,你就会看到差异。 - Jon Skeet