将一个字符串数组复制到另一个
如何从另一个string[]
复制string[]
?
假设我有string[] args
。 如何将其复制到另一个数组string[] args1
?
为目标数组分配空间,使用Array.CopyTo():
targetArray = new string[sourceArray.Length]; sourceArray.CopyTo( targetArray, 0 );
例如:
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" }
以上答案显示浅层克隆; 所以我想我使用序列化添加了一个深层克隆示例; 当然,深度克隆也可以通过循环原始数组并将每个元素复制到一个全新的数组中来完成。
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); } }
测试深度克隆:
上述就是C#学习教程:将一个字符串数组复制到另一个分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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)); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1023861.html