简体   繁体   English

如何序列化继承内置c#类的对象?

[英]How can I serialize objects that inherit built-in c# classes?

I'm trying to create a function that will save the current state of my application to a file, and another function to load a saved file. 我正在尝试创建一个将应用程序当前状态保存到文件的函数,以及另一个加载已保存文件的函数。 Currently, all the information is contained within a single object, which in turn refers to other objects. 当前,所有信息都包含在单个对象中,而单个对象又指向其他对象。 I recently heard that C# has some built-in classes that help you serialize and deserialize your objects, so I did a little research and learned about DataContracts, mostly from this page: http://msdn.microsoft.com/en-us/library/ms731073.aspx 最近,我听说C#具有一些内置类,可帮助您序列化和反序列化对象,因此我做了一些研究,并从以下页面了解了DataContracts: http//msdn.microsoft.com/zh-cn/库/ms731073.aspx

Most of it works, except for the classes that implement built-in classes. 除实现内置类的类外,大多数方法都有效。 For example, I have an object that inherits System.Windows.DependencyObject, and when I try to serialize it, it complains that my class inherits a class that does not have the DataContract attribute. 例如,我有一个继承System.Windows.DependencyObject的对象,当我尝试对其进行序列化时,它抱怨我的类继承了一个不具有DataContract属性的类。

It makes sense to me why that would be a problem. 对我来说,这为什么会是一个问题很有意义。 When an object is being deserialized, its constructor is not called. 反序列化对象时,不会调用其构造函数。 If it inherits something that is not serializable, that might leave it in an invalid state. 如果它继承了不可序列化的内容,则可能使其处于无效状态。

I was wondering if this was possible: can I somehow tell the deserializer to call the base class's default constructor before deserializing my object? 我想知道这是否可行:我可以以某种方式告诉反序列化器在反序列化对象之前调用基类的默认构造函数吗? And then I would have to tell the serializer not to freak out. 然后我将不得不告诉序列化器不要害怕。

Can you create a data transer object that has all the properties you want to store, then populate that object with data from the framework object? 您是否可以创建一个具有所有要存储属性的数据转换器对象,然后使用框架对象中的数据填充该对象? Mark it as serialized, fire up the serialization class of your choice - and now you have all the info you need. 将其标记为已序列化,启动您选择的序列化类-现在您已拥有所需的所有信息。 You just need to re-populate the appropriate class after deserialization. 您只需在反序列化之后重新填充适当的类。

You may want to look into using a binary serializer or xml serializer instead of a data contract serializer for this one. 您可能要考虑使用二进制序列化器或xml序列化器,而不是使用数据协定序列化器。 If you're saving it to a file and don't need the file human-readable binary serialization nearly always works. 如果您将其保存到文件中并且不需要该文件,那么人类可读的二进制序列化几乎总是可行的。

See Binary Serialization , and in particular the Basic Serialization topic. 请参阅二进制序列化 ,尤其是基本序列化主题。 Also take a look at the XmlSerializer Class which will sometimes work where a DataContractSerializer doesn't. 还要看看XmlSerializer类该类有时在DataContractSerializer不能使用的地方起作用。

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

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