views:

49

answers:

4

I have 2 class:

public class ClassA

public class ClassB (from another namespace) : ClassA

I have xml files fill with ClassA.

How to cast it to ClassB while deserialization.

is it possible ??

+1  A: 

You can't cast a base class to a derived class - you can only cast derived classes back to their base classes (one-way).

pete the pagan-gerbil
A: 

When creating the XmlSerialiser, you need to do it from your ClassB, it will then deserialise as the class you wish.

It would be invalid to cast a base class as an instance of a derived class.

Rowland Shaw
+1  A: 

I tried this solution, i.e. applying an XmlRoot element specifying the same element name as the one in ClassA.
This should work:

using System;
using System.IO;
using System.Xml.Serialization;

[XmlRoot("ClassA")]
public class ClassA {
    [XmlElement]
    public String TextA {
        get;
        set;
    }
}

[XmlRoot("ClassA")] // note that the two are the same
public class ClassB : ClassA {
    [XmlElement]
    public String TextB {
        get;
        set;
    }

}

class Program {
    static void Main(string[] args) {

        // create a ClassA object and serialize it
        ClassA a = new ClassA();
        a.TextA = "some text";

        // serialize
        XmlSerializer xsa = new XmlSerializer(typeof(ClassA));
        StringWriter sw = new StringWriter();
        xsa.Serialize(sw, a);

        // deserialize to a ClassB object
        XmlSerializer xsb = new XmlSerializer(typeof(ClassB));
        StringReader sr = new StringReader(sw.GetStringBuilder().ToString());
        ClassB b = (ClassB)xsb.Deserialize(sr);

    }
}
Paolo Tedesco
I get error:Not expected element ClassAat this line:ClassB b = (ClassB)xsb.Deserialize(sr);
Then you should apply the [XmlRoot("ClassA")] attribute to class B. I'll update the code.
Paolo Tedesco
You might also need to use the [XmlInclude()] statement to tell it which classes could appear there.For example (although getting the type may be slightly different in C#, I only have a VB example to hand): [XmlInclude(GetType(ClassB))]
pete the pagan-gerbil
@phenevo: does the updated code do what you need?
Paolo Tedesco
A: 

It is all about it, that method SaveObjectInDatabase must be on ClassB, not on classA. That's why I wanna casting ClassA to ClassB, and I don't know how to deal with it :/