代码之家  ›  专栏  ›  技术社区  ›  Dave Van den Eynde

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

  •  22
  • Dave Van den Eynde  · 技术社区  · 17 年前

    给出以下示例:

    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。为什么呢?

    1 回复  |  直到 17 年前
        1
  •  52
  •   Michael Piendl    17 年前

    在类Foo中追加以下代码行

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

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

    推荐文章