0
public class MyStuff : ICloneable
{
    public int A {get;set;}
    public int B {get;set;}

    public object Clone()
    {
        MyStuff Copy = (MyStuff)MemberwiseClone();
        return Copy;
    }
}

ここで、MyStuff の配列があると仮定しましょう

MyStuff[] MyStuffObjs = PopulateMyStuff();

Clone メソッドを実装する MyStuffObjs のクローンを作成する最も迅速で簡単な方法は何ですか?

コレクションを反復処理して、それぞれをコピーできることを知っています。

List<MyStuff> NewStuff = new List<MyStuff>();
foreach(var Stuff in MyStuffObjs)
{
    NewStuff.Add(Stuff.Clone());
}
return NewStuff.ToArray();

きっともっと良い方法がありますか?

4

2 に答える 2

1

そのためにLinqを使用できます:

return MyStuffObjs.Select(item => (MyStuff)item.Clone()).ToArray();

このようなヘルパーメソッドを作成することもできます

public static class MyExtensions
{
    public static T[] DeepClone<T>(this T[] source) where T : ICloneable
    {
        return source.Select(item => (T)item.Clone()).ToArray();
    }
}

次のように使用します

return MyStuffObjs.DeepClone();
于 2015-10-27T17:45:56.803 に答える
0

Just Select/ToArrayの方が短くなりますが、実際には、すべてのアイテムを繰り返し処理してClone.

短いコード:

 return MyStuffObjs.Select( x=> x.Clone()).ToArray();

少し高速なコード - リストを使用する代わりに配列を事前に割り当てます。

MyStuff[] cloned = new MyStuff[MyStuffObjs.Length];
for (var i = 0; i < cloned.Lenght; i++)
{
    cloned[i] = MyStuffObjs[i].Clone();
}
于 2015-10-27T17:47:56.530 に答える