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