【问题标题】:C# - Binary Serialization InvalidCastExceptionC# - 二进制序列化 InvalidCastException
【发布时间】:2017-01-07 15:47:38
【问题描述】:

所以我有一个名为 OutputInformation 的类,我想存储它,然后在另一台计算机上读取以检索数据。

我正在使用二进制序列化。

[Serializable()]
public class OutputInformation
{
    public List<string> filenames { get; set; }
    public long[] filesizes { get; set; }
}

public void Write()
{
    OutputInformation V = new OutputInformation();
    V.filesizes = sizearray;
    V.filenames = namelist;
    IFormatter formatter = new BinaryFormatter();
    Stream stream = new FileStream("D:\\MyFile.bin", FileMode.Create, 
                         FileAccess.Write, FileShare.None);
    formatter.Serialize(stream, V);
    stream.Close();
}

序列化在用户控件中完成,如果我在用户控件中反序列化,它工作正常。

但是如果我尝试从我的主窗口反序列化,我会得到一个 invalidcastexception。所以我想如果我尝试从另一台计算机反序列化文件,也会出现同样的问题。

我该如何解决这个问题?我只需要将类存储在一个文件中,然后从另一台计算机中检索它。最好不要使用 XML 序列化。

[Serializable()]
public class OutputInformation
{
    public List<string> filenames { get; set; }
    public long[] filesizes { get; set; }
}

IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("D:\\MyFile.bin", FileMode.Open, 
                                          FileAccess.Read, FileShare.Read);
OutputInformation obj = (OutputInformation)formatter.Deserialize(stream);
stream.Close();

错误是一个 InvalidCastException。附加信息:[A]OutputInformation 不能转换为 [B]OutputInformation。

【问题讨论】:

    标签: c# serialization binary-serialization


    【解决方案1】:

    两个类应该在同一个命名空间中。在与序列化完全相同的命名空间中定义您的 OutputInformation 类反序列化(或使用它引用程序集)。

    或者,如果不可能,或者您不想这样做,您应该编写自己的 SerializationBinder 实现

    public class ClassOneToNumberOneBinder : SerializationBinder
    {
        public override Type BindToType(string assemblyName, string typeName)
        {
            typeName = typeName.Replace(
                "oldNamespace.OutputInformation",
                "newNamespace.OutputInformation");
    
            return Type.GetType(typeName);
        }
    }
    

    并在反序列化之前设置:

    formatter.Binder = new ClassOneToNumberOneBinder();
    

    查看这里了解更多详情:Is it possible to recover an object serialized via "BinaryFormatter" after changing class names?

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 2017-10-18
      • 2010-12-17
      • 2015-09-17
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 2012-06-15
      相关资源
      最近更新 更多