GetObjectData() method is never hit when implement

2020-08-12 18:09发布

问题:

XmlSerializer never calls GetObjcetData() on my ISerializable. When is GetObjectData() called? Thanks!

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:

XmlSerializer doesn't call GetObjectData. Binary and soap do. If you want to manage xml serialization, use IXmlSerializable instead