反序列化过程中找不到构造函数? [英] Constructor not found during deserialization?

查看:86
本文介绍了反序列化过程中找不到构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下示例:

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);
        }
    }
}

在最后一行,由于格式器找不到Foo的构造函数,因此引发了SerializationException.为什么会这样?

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

推荐答案

在Foo类中添加以下代码行

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.

这篇关于反序列化过程中找不到构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆