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

+1

您没有通过分配引用来获得“真正的”父对象。您将不得不创建一个新的Parent对象,并从Child对象的相应属性中分配其属性。更好的是通过XML来实现而不是通过XML序列化,而不是让XML序列化器在反序列化时忽略序列化对象的实际类型(通过xsi:type指定的XML)很容易。 –

+0

[How to XML serialize child class with its base class](http://stackoverflow.com/questions/4943360/how-to-xml-serialize-child-class-with-its-base-class) – svick

+0

“你将不得不创建一个新的Parent对象,并从Child对象的相应属性中分配它的属性。”你能推荐一个简单的方法来为一个巨大的课程做到这一点吗?反思也许? – Milos

回答

2

你需要添加[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 { 
...