在反序列化期间找不到构造函数?

Dav*_*nde 23 .net c# serialization

给出以下示例:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*ndl 52

在类Foo中附加以下代码行

public Foo() {

}

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

}
Run Code Online (Sandbox Code Playgroud)

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