Given a tree hierarchy, suppose it is the following:
abstract class Person : ICloneable
...
sealed class Student : Person
...
I want to implement the ICloneable interface. In the Student.Clone method I wish to do something like:
{
Student clonedStudent = base.Clone() as Student;
clonedStudent.x1 = this.x1;
return clonedStudent
}
Because Person is abstract I can't create a Person in the Person.Clone() method, so I can't return a cloned Person, so I can't clone a Person.
The best answer I have figured out is to overload the Clone() method in the Person class to receive a Person, clone and return it. Then in the Student.Clone implementation call this overload to clone the person's related fields. Something like this:
//In the Person class:
public abstract object Clone();
protected Person Clone(Person clonedPerson)
{
// Clone all person's fields
return clonedPerson:
}
//In the Student class:
public override object Clone()
{
Student clonedStudent = base.Clone(new Student()) as Student;
// Clone all student's fields
return clonedStudent
}
Of course if any of the above class required to build any logic in its constructors this solution is more than useless. Any idea to implement a better one?
I think this is a subproblem of a more general one, so the answer will fit very well into a large superset.