2

我正在尝试像本示例中那样序列化父对象

static void Main(string[] args)
    {
        Child child = new Child
            {
                Id = 5,
                Name = "John",
                Address = "Address"
            };

        Parent parent = child;

        XmlSerializer serializer =new XmlSerializer(typeof(Parent));
        Stream stream=new MemoryStream();

        serializer.Serialize(stream,parent); //this line throws exception 

        Parent p2 = (Parent) serializer.Deserialize(stream);

        Console.ReadKey();
    }
}

[Serializable]
public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
}

[Serializable]
public class Child : Parent
{
    public string Address { get; set; }
}

我得到的异常文本是“类型 CastParrentExample.Child 不是预期的。使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。” 我想要达到的是在没有子类字段的情况下获得真正的父类对象。

4

2 回答 2

2

you need to add [XmlInclude(typeof(Child))] to parent class, as:

[XmlInclude(typeof(Child))]
public class Parent
{
    public int Id { get; set; }
    public string Name { get; set; }
}

or use following code while initializing XmlSeralializer:

XmlSerializer serializer =new XmlSeralializer(typeof(Parent), new[] {typeof(Child)})

for better understanding, see How to XML serialize child class with its base class.

于 2013-06-18T11:09:47.583 回答
2

在父类添加属性

[XmlInclude(typeof(Child))]
class Parent {
...
于 2013-06-18T11:05:15.433 回答