Given the following class:
class A
{
public List<B> ListB;
// etc...
}
where B
is another class that may inherit/contain some other classes.
Given this scenario:
A
is a large class and contains many reference types- I cannot mark
B
as[Serializable]
as I don't have access to source code ofB
The following methods to perform deep copying do not work:
- I cannot use
ICloneable
orMemberwiseClone
as classA
contains many reference types - I cannot write a copy constructor for
A
, as the class is large and continuously being added to, and contains classes (likeB
) that cannot be deep copied - I cannot use serialization as I cannot mark a contained class (like
B
, where no source code available) as[Serializable]
How can I deep copy class A
?
An answer from a different thread that using json serialization is the best I've seen.
You can try this. It works for me
Thanks to DetoX83 article on code project.
Try using a memory stream to get a deep copy of your object:
Here is more.
Pluss: Yoy can control copy process (if your class has identifier property you can set them, or you can write other business logic code)
Minus: class can be marked as sealed
Can't you do this?
And then refer to How do you do a deep copy of an object in .NET (C# specifically)? for a cloning function
I stopped using serialization for deep copying anyway, because there is not enough control (not every class needs to be copied the same way). Then I started to implement my own deep copy interfaces and copy every property in the way it should be copied.
Typical ways to copy a referenced type:
Example:
You may think that this a huge amount of work. But at the end, it is easy and straight forward, can be tuned where needed and does exactly what you need.