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;
    }
});