开发者

Casting xml to inherited class

开发者 https://www.devze.com 2022-12-21 08:08 出处:网络
I have 2 class: public class ClassA public class ClassB (from another namespace) : ClassA I have xml files fill with ClassA.

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 开发者_JAVA百科ClassB while deserialization.

is it possible ??


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);

    }
}


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消