簡體   English   中英

XmlSerializer c# 中的循環引用

[英]Circular Reference in XmlSerializer c#

我正在制作一個應用程序,我可以在其中將信號相互連接。 這將創建一個循環引用。 我看到的示例顯示了父子結構的解決方案。 在我的應用程序中,我將來自同一個 class 的 2 個對象相互連接,因此我不能簡單地忽略其中一個引用。

我做了一個簡單的例子來說明我的應用程序正在做什么:

class Program
{
    static void Main(string[] args)
    {
        Info i = new Info();
        Employee bs = new  Employee("asfdljfoiej", i);
        Employee ss = new Employee("asfdljfj", i);
        bs.conEm = ss;
        ss.conEm = bs;

        XmlSerializer xs = new XmlSerializer(typeof(Employee));
        const string path = @"C:\Users\Joris.Bosma.KG\source\repos\TestProject\TestProject\bin\Debug\Serializing.xml";
        TextWriter txtWriter = new StreamWriter(path);

        xs.Serialize(txtWriter, bs);

        txtWriter.Close();

        //---------------------------------------------------------------------------------------------------------------------------------------
        Program p = new Program();
        p.Deserialize("Serializing.xml");
    }
    public void Deserialize(string filename)
    {
        XmlSerializer xs2 = new XmlSerializer(typeof(Employee));
        Employee em;
        using (Stream reader = new FileStream(filename, FileMode.Open))
            em = (Employee)xs2.Deserialize(reader);
        Console.Write(em.name);

    }
}
public class Employee
{
    public int Id = 1;
    public String name = "John Smith";
    public string subject = "Physics";
    public string random;
    public List<Employee> Employees;
    public Employee conEm;
    public Info inf;
    public Employee()
    {

    }
    public Employee(String s, Info i)
    {
        random = s;
        inf = i;
    }

}
public class Info : Employee
{
    public string add = "Street";
}

問題出在bs.conEm = ss ss.conEm = bs

感謝您提前提供幫助!

如果員工的結構不是分層結構(可能存在循環),我建議從序列化中排除屬性“conEm”和“Employees”,並將數據存儲在如下結構中:

public class Relationship {
    public int ParentId { get; set; }
    public int ChildId { get; set; }
}

public class DataStore {
    // flat list of employees
    public List<Employee> Employees { get; set; }

    // list of all relationship between Employees
    public List<Relationship> Relationships { get; set; }
}

這個結構需要在序列化之前填充。

反序列化后,結構很容易恢復:

var index = data.Employees.ToLookup(e => e.Id);
data.Relationships.Iter(r => {
    var parent = index[r.ParentId].FirstOrDefault();
    var child = index[r.ChildId].FirstOrDefault();
    if (parent != nuu && child != null) {
       parent.Employees.Add(child);
       child.conEm = parent;
    }
});

暫無
暫無

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

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