给出以下示例:
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);
}
}
}
在最后一行中,抛出了SerializationException,因为格式化程序无法找到Foo的构造函数。那是为什么?
答案 0 :(得分:52)
在类Foo
中附加以下代码行public Foo() {
}
public Foo(SerializationInfo info, StreamingContext context) : base(info, context) {
}
该类需要一个带有相关序列化参数的构造函数。