Home » .Net技术 » [未找到反序列化“XXX”类型对象的构造函数。]的解决办法

[未找到反序列化“XXX”类型对象的构造函数。]的解决办法

出现[未找到反序列化“XXX”类型对象的构造函数。]错误一般是由于要反序列化的类或者它的父类(如:继承了Dictionary类)实现了ISerializable接口而没有序列化构造函数,这时候只要把序列化构造函数加上去就可以反序列化了。需要注意的是,一个类或者它的父类实现ISerializable接口就表示启用了自定义序列化,需要按照自定义序列化的规则编写序列化构造函数和GetObjectData函数,像下面的两个例子。

    [Serializable]
    class Test : ISerializable //实现了ISerializable接口
    {
        public Test()
        {
        }
 
        //实现了ISerializable接口的类必须包含有序列化构造函数,否则会出错。
        protected Test(SerializationInfo info, StreamingContext context)
        {
            Value = info.GetBoolean("Test_Value");
        }
 
        #region ISerializable 成员
 
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
            info.AddValue("Test_Value", Value);
        }
 
        #endregion
 
        public bool Value { get; set; }
    }
    [Serializable]
    class Test : Dictionary<string, string> //父类实现了ISerializable接口(Dictionary实现了ISerializable接口)
    {
        public Test()
        {
        }
 
        //父类实现了ISerializable接口的,子类也必须有序列化构造函数,否则反序列化时会出错。
        protected Test(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            Value = info.GetBoolean("Test_Value");
        }
 
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);
            info.AddValue("Test_Value", Value);
        }
 
        public bool Value { get; set; }
    }

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">