1

「SmallClass」という C# クラスがあります。

タイプ「SmallClass」のオブジェクトを含む既存のリスト myList があります

リスト「myList」のディープ クローンが必要です。つまり、含まれているリストをディープ クローンし、リストに含まれるオブジェクトをディープ クローンします。

どうすればいいですか。

    public class SmallClass: ICloneable {

    public string str1;
    public string str2;
    public string str3;

     public SmallClass Clone() //This just deep clones 1 object of type "SmallClass"
            {
                MemoryStream m = new MemoryStream();
                BinaryFormatter b = new BinaryFormatter();
                b.Serialize(m, this);
                m.Position = 0;
                return (SRO)b.Deserialize(m);
            }

      public override equals(Object a)
        {
                return Object.Equals(this.str1 && a.str1);
            }
    }

    public class AnotherClass
    {
           SomeCode();
           List<SmallClass> myList = new List<SmallList>();  //myList is initialized.


           // NOW I want to deep clone myList. deep Clone the containing list and deep clone the objects contained in the list.

         List<SmallClass> newList = new List<SmallClass>();
      foreach(var item in myList)
        {
           newList.Add((SmallClass)item.Clone());
        }       

}

4

3 に答える 3

6

警告: このBinaryFormatter型は、信頼できない入力で使用すると危険です。以下の使用法は安全ですが、Microsoftは誤用の可能性があるため完全に避けることを推奨しBinaryFormatterており、.NET 7–8 から削除します。ディープ クローンに別のシリアライザーまたはアプローチを使用することを検討してください。

まず、任意のオブジェクト (ルート) をディープ クローンするためのユーティリティ メソッドを定義できます。

public static T DeepClone<T>(T obj)
{
    using (var stream = new MemoryStream())
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, obj);
        stream.Position = 0;
        return (T)formatter.Deserialize(stream);
    }
}

deep-clone したい場合myListは、上記のメソッドにパラメーターとして渡すだけです。

List<SmallClass> myListClone = DeepClone(myList);

注意を払う必要がある最も重要な考慮事項は、すべてのクラスをシリアライズ可能としてマークする必要があるということです。通常、[SerializableAttribute].

[SerializableAttribute]
public class SmallClass
{
    // …
}
于 2012-05-16T19:22:13.637 に答える
4

SmallClass はICloneableインターフェイスを実装する必要があります。次に、Clone() メソッドを使用してすべての要素をコピーします。

List<SmallClass> newList = new List<SmallClass>();
foreach(var item in myList)
{
    newList.Add((SmallClass)item.Clone());
}
于 2012-05-16T19:10:05.637 に答える