Look at the Code Snippet below:
It is not possible to Deserialize the Animal in animalStr directly
because the type of the animal is not known. Deserializing into the
abstract type will not work because the xml serilization in animalStr
contains more than an Animal, it contains either Cat or Dog. Is there a
neat way of dealing with deserilization of abstract types?
------------- Code Snippet -------------
abstract public class Animal
{
public abstract string GetAnimalType();
}
public class Dog : Animal
{
public string type = "Dog";
public override string GetAnimalType()
{
return type;
}
}
public class Cat : Animal
{
public string type = "Cat";
public string CatColor = "Grey";
public override string GetAnimalType()
{
return type;
}
}
class Test
{
[STAThread]
static void Main(string[] args)
{
string animalStr="";
//animalStr contains an XML serilization of either Dog or Cat
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Animal));
StringReader stringReader = new StringReader(animalStr);
Animal animal = (Animal)xmlSerializer.Deserialize(stringReader);
Console.WriteLine("Animal type:{0}", animal.GetAnimalType());
}
}
------------- Possible Solution -------------
Maybe with the use of a helper object eventhough its not very neat:
class AbstractXMLObject{
public string type;// either "Cat" or "Dog"
public string xml; // serilization of either Cat or Dog
}
class Test
{
[STAThread]
static void Main(string[] args)
{
AbstractXMLObject abstractXMLObject = new AbstractXMLObject;
//abstractXMLObject type and xml is set
XmlSerializer xmlSerializer;
if abstractXMLObject.type=="Dog" {
xmlSerializer = new XmlSerializer(typeof(Dog));
}
if abstractXMLObject.type=="Cat" {
xmlSerializer = new XmlSerializer(typeof(Cat));
}
StringReader stringReader = new StringReader(animalStr);
Animal animal=(Animal)xmlSerializer.Deserialize(abstractX MLObject.xml);
Console.WriteLine("Animal type:{0}", animal.GetAnimalType());
}
}