anerjan / protobuf-net

Automatically exported from code.google.com/p/protobuf-net
Other
0 stars 0 forks source link

ProtoBuf-net AsReference require public constructor in Activator.CreateInstance. #232

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
This is a repeat post to the question posted at 
http://stackoverflow.com/questions/7219959/protobuf-net-asreference-require-publ
ic-constructor-in-activator-createinstance

The following class constructs produce a runtime error on deserialization in 
ProtoBuf.BclHelper while resolving parameterless constructor for Parent class.

using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using ProtoBuf;

namespace Sandbox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            Family family = new Family();
            Child child1 = new Child(1);
            Child child2 = new Child(2);
            Parent parent = new Parent(new List<Child>() { child1, child2 });
            family.Add(parent);

            string file = "sandbox.txt";

            try { File.Delete(file); } catch { }

            using (var fs = File.OpenWrite(file)) { Serializer.Serialize(fs, family); }
            using (var fs = File.OpenRead(file)) { family = Serializer.Deserialize<Family>(fs); }

            System.Diagnostics.Debug.Assert(family != null, "1. Expect family not null, but not the case.");
        }
    }

    [ProtoContract()]
    public class Child
    {
        [ProtoMember(1, AsReference = true)]
        internal Parent Parent;

        private Child() { }

        public Child(int i) { }
    }

    [ProtoContract()]
    public class Parent
    {
        [ProtoMember(1)]
        protected List<Child> m_Children;

        /// <summary>
        /// ProtoBuf deserialization constructor (fails here)
        /// </summary>
        private Parent() { m_Children = new List<Child>(); }

        public Parent(List<Child> children)
        {
            m_Children = children;
            m_Children.ForEach(x => x.Parent = this);
        }
    }

    [ProtoContract()]
    public class Family
    {
        [ProtoMember(1)]
        protected List<Parent> m_Parents;

        public void Add(Parent parent)
        {
            m_Parents.Add(parent);
        }

        public Family()
        {
            m_Parents = new List<Parent>();
        }
    }
}

Original issue reported on code.google.com by Jake...@gmail.com on 10 Sep 2011 at 5:21

GoogleCodeExporter commented 9 years ago
See: 
http://stackoverflow.com/questions/7219959/protobuf-net-asreference-require-publ
ic-constructor-in-activator-createinstance

Original comment by marc.gravell on 20 Oct 2011 at 9:54