简体   繁体   中英

Serializing a tree object in c#

I got a simple tree structure which contains the following

public class MyTree {
 public MyTree Parent { get; set;}
 public List<MyTree> Children {get; set;}
[...]
}

Currently the class is much more complex, but this is the important part to my problem I think. That code is quite old and I cannot just change the complete structure, because it is used in many areas in a project I have to maintain.

My main problem is that I cannot serialize that object. (I start serializing from root object) I get the following message:

A circular reference was detected while serializing an object of type MyTree

It seems quite clear why this happens because I have the children AND parent connected.

But how can I solve that problem? Can I disable serialization of the parent property for example?

Mark parent as not serialize item ( XmlIgnore , SoapIgnore or NonSerialized ). Check about different there .

In your case you add parent to xml, after this trying to add children. Each child has link to parent and serializer tries to serialize parent again and so on..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM