c# - XML serialize base class without knowing derived class -
I know that a XmlSerializer
throws an exception if the type passed does not match the type Since then the serializer was created
My question is: Is it possible to serial the base type without knowing the derivative type? Consider the following scenario:
The following classes are in a top-level domain and there is no dependency :
Public Class Serializer {Private Static String Serialize (base basedata) {var serializer = New XML serializer (typefile); Var sb = new stringbilder (); (Var author = XmlWriter.Create (sb)) using {serializer.Serialize (author, bassadata); } Return sb.ToString (); } Private static string Deserialize (...) {...}} Public class base {public string name {get; Set; }}
The following derivative classes have additional dependencies on things like UI components, structure, etc. (and more on this later):
< Pre> [Export (Typ (IMyComponent)] Public category was created: Base, IMyComponent, INotifyPropertyChanged {public new string name {get {return base.Name; } Set {base.Name = value; NotifyPropertyChanged ("name"); }}}
If I call the serializer like this:
base myData = new derived (); MyData.Name = "Foo Bar"; Serializer.Serialize (MyData);
This throws an exception because I have passed in a derived
, although parameters and serializers are clearly set to Base
I want to serialize base
, I do not care that is in derivative
.
My goal here is to create a derivative class, but a sort the base class only The reason for this is that I am deserializing XML in the separate assembly in which There should not be any additional dependencies beyond the .net framework. Serializer and base objects have been rebuilt / reproduced in this separate assembly so that the namespace and the type will match, so when deserialization occurs then the type will be deserialized correctly, but I
So, how can I serialize the serialization base class even if I am in a derivative class? Again, I do not care if I have lost the information in the derivative
, then I am worried that this is the base
.
Since you are only serialing the base property, you have to make an example of the base and generate the type Mapping the properties from Serializers are programmed to be smart, sometimes very smart in your case.
View in Automapor or do it manually.
public class serializer {Private Static String Serialize (base BaseData) {var map = base = new; // Mapping MapBase Foo = bassadata.fu; Var serializer = New XmlSerializer (typef (base)); Var sb = new stringbilder (); (Serializer.Serialize (Author, Mapped) using (Var Writer = XmlWriter.Create (sb)); } Return sb.ToString (); } Personal static string deserialize (...) {...}}
Comments
Post a Comment