.NET XmlSerializer and multiple references to the same object

前端 未结 5 606
你的背包
你的背包 2021-01-05 04:52

My repository has List, List and List where an Enrolment has Enrolment.Student and Enrol

5条回答
  •  萌比男神i
    2021-01-05 05:31

    You should/can use Reference Tracking with the datacontract serializer:

    //deserilaize:
    using(MemoryStream memStmBack = new MemoryStream()) {
      var serializerForth = new DataContractSerializer(
        typeof(YourType),
        null,
        0x7FFF /*maxItemsInObjectGraph*/ ,
        false /*ignoreExtensionDataObject*/ ,
        true /*preserveObjectReferences*/ ,
        null /*dataContractSurrogate*/ );
    
      byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
      memStmBack.Write(data, 0, data.Length);
      memStmBack.Position = 0;
      var lsBack = (YourType) serializerForth.ReadObject(memStmBack);
    
    }
    //serialize...
    using(MemoryStream memStm = new MemoryStream()) {
        var serializer = new DataContractSerializer(
          typeof(YourType),
          knownTypes,
          0x7FFF /*maxItemsInObjectGraph*/ ,
          false /*ignoreExtensionDataObject*/ ,
          true /*preserveObjectReferences*/ ,
          null /*dataContractSurrogate*/ );
    
        serializer.WriteObject(memStm, yourType);
    
        memStm.Seek(0, SeekOrigin.Begin);
    
        using(var streamReader = new StreamReader(memStm)) {
            result = streamReader.ReadToEnd();
    

    Or use

    [Serializable]
    [DataContract(IsReference = true)]
    

提交回复
热议问题