C# - 二进制序列化 InvalidCastException

标签 c# serialization binary-serialization

所以我有一个名为 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();
}

序列化是在用户控件中完成的,如果我在用户控件中反序列化,它工作得很好。

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

如何解决这个问题?我只需要将类存储在一个文件中,然后从另一台计算机上检索它。最好不要使用 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。

最佳答案

两个类应该位于同一命名空间中。在反序列化时定义您的 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?

关于C# - 二进制序列化 InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41523222/

相关文章:

c# - c# 中的常量和只读?

c# - 我如何对 List<int> 进行分组并返回 List<int>

java - 用于标记字符串的正则表达式

php - 如何附加数据库中已存在的序列化字符串

Java:使用反射从数字实例化枚举

ruby - 在 Ruby 中使用 Marshal::dump 进行对象序列化时如何写入文件

c# - WPF、WinForms、ActiveX 控件和我正在消失的理智(调用 DragMove() 以响应 WinForms 控件的 MouseDown 事件)

c# - Regex或Linq在c#中捕获键值对

java - Jackson 无法序列化 Joda DateTimeFormatter

c# - 如何使用 protobuf-net 或其他序列化程序序列化第 3 方类型?