XmlSerializer c#中的循环引用>> [

问题描述 投票:0回答:1
我正在制作一个将信号相互连接的应用程序。这将创建一个循环引用。我看过的示例显示了父子结构的解决方案。在我的应用程序中,我将来自同一类的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个回答
0
投票
如果员工的结构不是分层结构(可能出现循环),我建议从序列化中排除属性'conEm'和'Employees'并将数据存储在这样的结构中:
© www.soinside.com 2019 - 2024. All rights reserved.