I have a requirement to map all of the field values and child collections between ObjectV1 and ObjectV2 by field name. ObjectV2 is in a different namspace to ObjectV1.
Inheritence between the template ClassV1 and ClassV2 has been discounted as these 2 classes need to evolve independently. I have considered using both reflection (which is slow) and binary serialisation (which is also slow) to perform the mapping of the common properties.
Is there a preferred approach? Are there any other alternatives?
clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.
In general, when we try to copy one object to another object, both the objects will share the same memory address. Normally, we use assignment operator, = , to copy the reference, not the object except when there is value type field. This operator will always copy the reference, not the actual object.
You don't make a deep copy using list() .
As an alternative to using reflection every time, you could create a helper class which dynamically creates copy methods using Reflection.Emit - this would mean you only get the performance hit on startup. This may give you the combination of flexibility and performance that you need.
As Reflection.Emit is quite clunky, I would suggest checking out this Reflector addin, which is brilliant for building this sort of code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With