【问题标题】:Serialization of parent object父对象的序列化
【发布时间】:2013-06-18 19:16:56
【问题描述】:

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

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 属性指定静态未知的类型。” 我想要达到的是在没有子类字段的情况下获得真正的父类对象。

【问题讨论】:

  • 您没有通过分配引用获得“真正的”父对象。您必须创建一个新的 Parent 对象并从 Child 对象的相应属性中分配其属性。手动完成比 XML 序列化好,并不是说在反序列化时很容易让 XML 序列化程序忽略序列化对象的实际类型(通过 xsi:type 在 XML 中指定)。
  • "您必须创建一个新的 Parent 对象并从 Child 对象的相应属性中分配其属性。"你能推荐一个简单的方法来为一个庞大的班级做这件事吗?反射可能吗?

标签: c# .net


【解决方案1】:

你需要在父类中添加[XmlInclude(typeof(Child))],如:

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

或在初始化 XmlSeralializer 时使用以下代码:

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

为了更好地理解,请参阅How to XML serialize child class with its base class

【讨论】:

    【解决方案2】:

    在父类添加属性

    [XmlInclude(typeof(Child))]
    class Parent {
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      相关资源
      最近更新 更多