简体   繁体   English

C#将对象保存到文件或从文件加载对象:单个实例

[英]C# Save/Load objects to/from files: single instances

I am working on a windows application tool. 我正在使用Windows应用程序工具。 The tool lets the user build data. 该工具允许用户构建数据。
I am looking for a way to save the user's work into a file. 我正在寻找一种将用户的工作保存到文件中的方法。 I heard about XML serialisation, but I haven't found an answer to the following question: 我听说过XML序列化,但是没有找到以下问题的答案:

Say I have 2 lists, and there are objects that are referenced to from both lists (both lists point to the same instance of the object). 假设我有2个列表,并且两个列表都引用了这些对象(两个列表都指向该对象的同一实例)。 If I go over both lists to save all the objects, will that object be saved only once, since it is a single instance, or will it be saved twice, since it is referenced to from both lists? 如果我同时浏览两个列表以保存所有对象,那么由于它是单个实例,该对象将仅保存一次,还是因为两个列表都引用了该对象而将其保存两次?

Also, when loading the file, I want to be able to know that it was a single object and that it was referenced to from both lists (basically load up the exact memory image I had before). 另外,在加载文件时,我希望能够知道它是单个对象,并且从两个列表中都对其进行了引用(基本上加载了我之前拥有的确切的内存映像)。

Can XML serialisation do that in C#? XML序列化可以在C#中做到吗?
Or if there's a better way, what is it? 或者,如果有更好的方法,那是什么?

Thanks, M. 谢谢,M

The XmlSerializer will not retain object references. XmlSerializer将不会保留对象引用。 After you deserialize, object.ReferenceEquals will return false, where it would've returned true before serialization. 反序列化之后, object.ReferenceEquals将返回false,在序列化之前它将返回true。

What you need to use is a DataContractSerializer and set PreserveObjectReferences , this will solve your case. 您需要使用DataContractSerializer并设置PreserveObjectReferences ,这将解决您的情况。

Alternatively, if you must use XML, you can add attributes yourself and use the deserialize events to re-instantiate any object references, but this requires quite some work. 另外,如果必须使用XML,则可以自己添加属性,并使用反序列化事件重新实例化任何对象引用,但这需要进行大量工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM