On 2006-08-23 15:48:35 -0400, Thomas Lorenz <thomas.lorenz@gmx.desaid:
Quote:
Hi
>
I have a class Person and a class Student which inherits from Person. Each
class should have a method which copies the properties from another Person
or Student respectively. The copy-method of Student should override the one
of Person and call it as well.
You did not spell out why you want this; if you simply want to clone
Students, like this--
Student doyle = new Student();
// set properties of doyle here, then clone him
Student crabbe = doyle.Clone();
// change some properties of crabbe here
--then IClonaeable is the way to go. OTOH, If you want to clone a
Person into a Student, that's wrong because Person lacks the properties
of Student and thus cannot clone into a fully developed student. You
might try a hierarchy of assignment mehods for that purpose.
Anyway, back to cloning. O'Reilly's book, .NET Gotchas, recommends
something like this:
public class Person :
ICloneable
{
protected Person ( Person other ) {
// Copy Person attributes
}
public virtual object Clone() {
return new Person( this );
}
}
public class Student :
Person
{
protected Student( Student other ) :
base( other ) // <---- This copies Person attributes
{
// Copy Student attributes
}
public override object Clone() {
return new Student( this );
}
}
The key that makes it all work is the PROTECTED copy constructor in each class.