C# 反序列化期间未找到构造函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/673444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:51:02  来源:igfitidea点击:

Constructor not found during deserialization?

c#.netserialization

提问by Dave Van den Eynde

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?

在最后一行中,由于格式化程序找不到 Foo 的构造函数,因此抛出了 SerializationException。这是为什么?

采纳答案by Michael Piendl

Append the following code lines in the class Foo

在 Foo 类中添加以下代码行

public Foo() {

}

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

}

The class needs an constructor with the relevant serialisation parameters.

该类需要一个带有相关序列化参数的构造函数。