实现ISerializable时,永远不会遇到GetObjectData()方法

时间:2012-03-30 20:33:39

标签: c# .net serialization

XmlSerializer从不在GetObjcetData()上致电ISerializable。什么时候被叫GetObjectData()?谢谢!

class Program
{
  static void Main(string[] args)
  {
    var thing = new Thing { Name = "Dude", Id = 1 };
    var xmlSerializer = new XmlSerializer(typeof(Thing));

    var sw = new StringWriter();
    xmlSerializer.Serialize(sw, foo);
    var serializedXml = sw.ToString();

    var sr = new StringReader(serializedXml);
    var result = (Thing)xmlSerializer.Deserialize(sr);
  }        
}

public class Thing : ISerializable
{
  public string Name { get; set; }
  public int Id { get; set; }

  public Thing() { }        
  public Thing(SerializationInfo info, StreamingContext context) { }

  public void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    // Breakpoint placed on the following line never gets hit:
    throw new NotImplementedException();
  }
}

1 个答案:

答案 0 :(得分:18)

XmlSerializer不会调用GetObjectData。二进制和肥皂呢。 如果要管理xml序列化,请使用IXmlSerializable代替