Tuesday 15 April 2014

.net - How to serialize a derived class as its base class -


I have a derived class that only connects to the base class methods that can serialize the derived class so that it can be classified as base class Matches the serialization. That is, the ordering XML of a derived class should look like this:

  & lt; Base Class & gt; ... & lt; / Base Class & gt; For example, an invalid operation exception will be thrown in the following. "Type DerivedClass was not expected. To specify the type of XmlInclude or Use the SoapInclude attribute, which are definitely not known. " Class BaseClass {} Category DerivedClass: BaseClass {} DerivedClass derived = new DerivedClass (); Streamer stream = new streamer ("output file path"); XmlSerializer serializer = New XmlSerializer (GetType (BaseClass)); Serial (stream, derivative);  

You have to pass GetType (DerivedClass) to the Serializer constructor, it is necessary by you Match the sorted object type You can change the code in the & lt; XmlRoot & gt; You can use the attribute. This example code works as a purpose:

  using the system; Using System.Xml.Serialization; Using System.IO; Class program {static zero main (string [] args) {var obj = new DerivedClass (); Obj.Prop = 42; Var xs = New XmlSerializer (type (DerivedClass)); Var sw = new stringwriter (); Xs.Serialize (SW, obj); Console.WriteLine (sw.ToString ()); Var sr = new stringreader (sw.ToString ()); Var obj2 = (Base Class) xs.Deserialize (sr); Console.ReadLine (); }} Public Class Base Class {Public Ent Prote {get; Set; }} [XmlRoot ("BaseClass")] Public Category DerivedClass: BaseClass {}  

No comments:

Post a Comment