| Bruce Wood 2005-05-02, 8:58 pm |
| What it looks like you want is a Clone method. Look at the ICloneable
interface.
If you want a good, general way of implementing Clone() that takes
inheritance into account, try this:
// If your type doesn't have a "no arguments" constructor then make a
protected one
// that doesn't do anything, and document the fact that it's for use
only in the Clone()
// method.
protected MyType()
{ }
public MyType Clone()
{
MyType result = new MyType();
this.CopyTo(result);
return result;
}
protected CopyTo(MyType other)
{
// If you're inheriting from another one of your classes that has
// a CopyTo method, then you need to say
// base.CopyTo(other);
// here.
other.field1 = this.field1;
other.field2 = this.field2;
...
}
I wouldn't bother with a generic solution using Reflection. First of
all, Reflection comes with a performance penalty. Second, you'll leave
other programmers scratching their heads... ICloneable is a familiar
idiom that everyone will understand, even if it means writing code in
every class.
|