gpt4 book ai didi

c# - 父对象的序列化

转载 作者:行者123 更新时间:2023-11-30 20:57:01 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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

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

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

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

关于c# - 父对象的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17167153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com