开发者

C# Deep Copying Tree Structures with BinaryFormatter

EDIT 1

Kent has alleviated my fears. However, I've found one exception to the rule. I wrote a method for the Node class that would traverse up through the hierarchy until it got to the root Node and return its hash code. The hash code's the same all the way down the line except for one single object. In a word, RAGE.


I'm at the end of writing my first (relatively) large C# application. However, I think I've found a major bug that I screwed up on.

My app parses an XML file and creates a hierarchy of objects, each inheriting from a Node class, with Lists of Children and a Node Parent reference.

I needed to be able to copy this structure over. The c开发者_C百科oncept is the initial structure holds the default data, and you can get your own copy and modify it while you use it. So I used a generic DeepClone< T > extension method to do it with BinaryFormatter.

My question, although I feel I already know (and dread) what the answer, is does this sill leave me with the problem of reassigning the references of all those Parent and Child nodes?


Disclaimer: As I finish this, I'm realizing all the design mistakes I made and how they could have been avoided, including this one. In my defense, this semester at university will be the first time I take a data structures class. ;) I fully expect there to be some vital part of a tree that I failed to implement that would help solve this. >_<


No. The serialization process records the references between objects and the deserialization process restores those relationships.

EDIT: unless I misunderstood your question - it's not exactly clear what you meant. Once the client code has made changes to the cloned structure, it is up to you to incorporate those changes into the main data structure, if that's what you want to do.

You might want to take a look at IEditableObject for a more formalized way to handling this kind of thing. You may well continue to use serialization as your means of cloning the object prior to edits, but your interface will be more standardized.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜