简体   繁体   中英

XML Serialization – serialize the properties in user control

How to serialize the properties in user control?

I have tried the following code but I got InvalidOperationExceptio, While creating the XmlSerializer object

MyUserControl userControl = new MyUserControl();
XmlSerializer serializer = new XmlSerializer(typeof(MyUserControl));
Stream stream = new MemoryStream();
TextWriter writer = new StreamWriter(stream);
serializer.Serialize(writer, userControl);   

Exception:

System.InvalidOperationException was unhandled

HResult=-2146233079

Message=There was an error reflecting type 'Demo.MyUserControl'.

You should not do it like this IMHO.

You should write a separate "Data Transfer Object (DTO)" style class to hold the data that you want to serialize, and use that instead. (You'd need to write Transform methods to convert the data back and forth of course.)

Otherwise you will couple your data storage format tightly to your user control.

If you use a separate class for serializing, it will make it much more manageable and flexible especially if you need to add new properties in the future.

If you really must serialize the user control (and I highly recommend that you don't ) you could try using DataContract serialization which has an "opt-in" mechanism for which properties get serialized, rather than the "opt-out" mechanism for the older serialization.

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