简体   繁体   中英

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

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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