S
Stuart
How to clone objects which contain other objects and collections.
1. In top level class (Class1), write a clone method as follows:
public object Clone()
{
Class1 object=(Class1)this.MemberwiseClone();
//clone objects within this class
object.Object2=(Class2)this.Object2.Clone();
//Also clone any collection objects
object.Collection1=(CollectionClass)this.Collection1.Clone();
return object;
}
2. For the objects within this class (Class1).
a. Inherit the class from Icloneable by adding ": ICloneable" after
class defn.
b. Add clone method
public object Clone()
{
return this.MemberwiseClone();
}
3. For collections within this class (Class1).
a. Inherit the collection from Icloneable by adding ": ICloneable"
after class defn.
b. Add clone method
public object Clone()
{
return new Collection1(this);
}
c. Write a constructor for collection that takes itself as a parameter
public Collection1(ICollection collection)
{
foreach (CollectionClassObject o in collection)
{
this.Add((CollectionClassObject)o.Clone());
}
}
d. Add a clone method to the CollectionClassObject
public object Clone()
{
return this.MemberwiseClone();
}
4. Ensure that all the objects within the top-level class (Class1)
have all their inner objects and collections cloned too. i.e.
Class1.Object1.Object1 is cloned etc.
1. In top level class (Class1), write a clone method as follows:
public object Clone()
{
Class1 object=(Class1)this.MemberwiseClone();
//clone objects within this class
object.Object2=(Class2)this.Object2.Clone();
//Also clone any collection objects
object.Collection1=(CollectionClass)this.Collection1.Clone();
return object;
}
2. For the objects within this class (Class1).
a. Inherit the class from Icloneable by adding ": ICloneable" after
class defn.
b. Add clone method
public object Clone()
{
return this.MemberwiseClone();
}
3. For collections within this class (Class1).
a. Inherit the collection from Icloneable by adding ": ICloneable"
after class defn.
b. Add clone method
public object Clone()
{
return new Collection1(this);
}
c. Write a constructor for collection that takes itself as a parameter
public Collection1(ICollection collection)
{
foreach (CollectionClassObject o in collection)
{
this.Add((CollectionClassObject)o.Clone());
}
}
d. Add a clone method to the CollectionClassObject
public object Clone()
{
return this.MemberwiseClone();
}
4. Ensure that all the objects within the top-level class (Class1)
have all their inner objects and collections cloned too. i.e.
Class1.Object1.Object1 is cloned etc.