我正在尝试像本示例中那样序列化父对象
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 属性指定静态未知的类型。” 我想要达到的是在没有子类字段的情况下获得真正的父类对象。