开发者

StackOverFlowException during Serialization

I trying to serialize a custom type which holds a dictionary among o开发者_开发技巧ther members. The types associated with key and value of the dictionary are interfaces which are implemented.

The dictionary looks like

 Dictionary<ITypeA, ITypeA> 

TypeA implements ITypeA, 
SubTypeOfA inherits from TypeA
SubTypeOfB inherits from SubTypeOfA

pseudo code looks something like this:

            List<Type> knownTypes = new List<Type>() { 
                typeof(TypeA), 
                typeof(SubTypeOfA),
                typeof(SubTypeOfB)
            };

DataContractSerializer serializer =
                new DataContractSerializer(typeof(DataHolder), knownTypes);

            using (FileStream fs = new FileStream(completeFilePath, FileMode.Create))
            {
                serializer.WriteObject(fs, templateData);
                success = true;
            }

I get a StackOverflowException when WriteObject() is getting called, am clueless on what is causing that to happen.

All the classes in the hierarchy are decorated with [DataContract] and the members to be serialized are decoreated with [DataMember].

Any help would be appreciated.


I might expect something like this if you have a cycle in the graph, but which is somehow not detected as an object identity failure. By cyclic, I mean:

using System.Runtime.Serialization;
[DataContract] class Foo {
    public Foo() { Bar = this; }
    [DataMember] public Foo Bar { get; set; }
    static void Main() {
        new DataContractSerializer(typeof(Foo)).WriteObject(
            System.IO.Stream.Null, new Foo());
    }
}

which throws the error:

Object graph for type 'Foo' contains cycles and cannot be serialized if reference tracking is disabled.

This is because it is trying to walk the tree (not a graph), and noticing a repeat (identical object reference), and stopping. However, by testing the above (and seeing when the get is called), it looks like DCS actually does this by spotting pain - the depth before it aborts is very high.

Locally, I get 528 calls to Bar before it dies. If you already have complex code above this in the stack, it could account for a stack overflow, for sure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜