I found
an interesting solution for creating a deep copy of an object
in .NET
using serialization. Eager to test it out, I wrote the following code in my Foo class:
public
Foo Copy()
{
Foo copy = null;
using(MemoryStream memStream =
new MemoryStream())
{
BinaryFormatter formatter = new
BinaryFormatter();
formatter.Serialize(memStream, this);
memStream.Seek(0, SeekOrigin.Begin);
copy = (Foo) formatter.Deserialize(memStream);
}
return copy;
}
Of course, in order to make this work, I had to use the [Serializable] attribute
on Foo plus the classes it utilized internally. Alas, upon trying to create a
copy with my cool new method, I got a nice little exception, ""Serialization
will not deserialize delegates to non-public methods." At first I just assumed
that the "free serialization" I get from the framework via [Serializable]
attribute would have to be replaced with implementing the
ISerializable
attribute and writing my "roll-your-own" serialization code with the GetObjectData method. It turns out that the exception was being thrown because
of a public event field that I had exposed in class contained within Foo
named Bar. (NOTE: I'm changing the names of my classes to "protect the
innocent")
public
delegate void
BarAddedHandler(Bar bar);
public
event BarAddedHandler BarAdded;
It turns out that
you can simply apply the [NonSerialized] attribute using the "field:"
qualifier to avoid this problem.
[field:NonSerialized]
public
event BarAddedHandler BarAdded;
Anyone have a better idea for handling either the deep copy problem or the
serialization issue? I'm always looking for good (and better) ideas, so let me
know what you think. :-)