[英]C# - Binary Serialization InvalidCastException
所以我有一個名為 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。
兩個類都應該在同一個命名空間中。 在與序列化完全相同的命名空間中定義您的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();
在此處查看更多詳細信息: 是否可以在更改類名后恢復通過“BinaryFormatter”序列化的對象?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.