簡體   English   中英

如何在c#中使用循環依賴項將對象序列化為xml?

[英]How to serialize object to xml with circular dependency in c#?

我有一個具有循環依賴關系的對象

    public class Levels
    {
        public UserDescription user { get; set; }
        public List<Levels> friends {get; set;}

        public Levels(UserDescription user, List<Levels> friends)
        {
           this.user = user;
           this.friends = friends;
        }

        public Levels() { }            
    }

我需要將其序列化為xml,因此請執行以下操作:

    public string SerializeObject(object obj)
    {
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
        {
            serializer.Serialize(ms, obj);
            ms.Position = 0;
            xmlDoc.Load(ms);
            return xmlDoc.InnerXml;
        }
    }

此代碼在serializer = new System.Xml.Serialization.XmlSerializer上引發異常System.InvalidOperationException。 我該如何解決?

問題在於類UserDescription沒有空的構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM