Datacontract serialization error

2019-09-10 00:46发布

问题:

This is the continuation of How to set [DataMember] on all class members

So I have to serialize a class with dictionaries and other members.

I have chonse the datacontext serialization that se

public SimpleDataGridSample()
    {
      if (false)
      {

        MyClass theclass = new MyClass();

        var serializer = new DataContractSerializer(typeof(MyClass));

        using (Stream fileStream = File.Open("aaa.bin", FileMode.Create))
        {
          XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(fileStream);
          serializer.WriteObject(binaryDictionaryWriter, theclass);
          binaryDictionaryWriter.Flush();
        }
      }
      else
      {
        MyClass theclass;
        var serializer = new DataContractSerializer(typeof(MyClass));

        using (Stream fileStream = File.Open("aaa.bin", FileMode.Open))
        {
          XmlDictionaryReaderQuotas xq = new XmlDictionaryReaderQuotas();
          XmlDictionaryReader binaryDictionarReader = XmlDictionaryReader.CreateBinaryReader(fileStream, xq);
          theclass = (MyClass)serializer.ReadObject(binaryDictionarReader);

        }
      }

    }
  }

and that worked.

But that was just a test program. When applying to my class which is more complicated I get this error:

{"Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}

Can't understand what index is talking about.

The main class is made of serveral members (also dictionaries and observable lists) and other sub classes. Every class is marked [DataContract(IsReference = true)] and every member is marked [DataContext]

Thanx

回答1:

OK that was IMPOSSIBLE for other users to aswer. At first I didn't understand where the problem was because I never used used DataContract serialization before and was not proficent about it. But it works! What put me on track was the good old intellisense. This is the variable after having been created and it contains the exception. Thank you the same