Constructor not found during deserialization?

泄露秘密 提交于 2019-12-21 03:14:12

问题


Given the following example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace SerializationTest
{
    [Serializable]
    class Foo : Dictionary<int, string>
    {
    }

    class Program
    {
        static void Main(string[] args)
        {
            Foo foo = new Foo();
            foo[1] = "Left";
            foo[2] = "Right";

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();

            formatter.Serialize(stream, foo);
            stream.Seek(0, SeekOrigin.Begin);
            formatter.Deserialize(stream);
        }
    }
}

In the last line, a SerializationException is thrown because the formatter can't find the constructor to Foo. Why is that?


回答1:


Append the following code lines in the class Foo

public Foo() {

}

public Foo(SerializationInfo info, StreamingContext context) : base(info, context) {

}

The class needs an constructor with the relevant serialisation parameters.



来源:https://stackoverflow.com/questions/673444/constructor-not-found-during-deserialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!