【问题标题】:Circular Reference in XmlSerializer c#XmlSerializer c#中的循环引用
【发布时间】:2020-05-13 10:25:27
【问题描述】:

我正在制作一个应用程序,我可以在其中将信号相互连接。这将创建一个循环引用。 我看到的示例显示了父子结构的解决方案。在我的应用程序中,我将来自同一类的 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

感谢您提前提供帮助!

【问题讨论】:

    标签: c# circular-reference


    【解决方案1】:

    如果员工的结构不是分层结构(可能存在循环),我建议从序列化中排除属性“conEm”和“员工”,并将数据存储在如下结构中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多