当序列化和InvalidCastException的反序列化 [英] InvalidCastException when serializing and deserializing
问题描述
我有这样的代码:
public byte[] SerializeToBlob()
{
using (var buffer = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(buffer, this);
buffer.Position = 0;
return buffer.ToArray();
}
}
public static ActionData DeserializeFromBlob(byte[] state)
{
using (var buffer = new MemoryStream(state))
{
var formatter = new BinaryFormatter();
var result = formatter.Deserialize(buffer);
return (ActionData) result;
}
}
和我打电话,如下所示:
And am calling it as follows:
byte[] actionDataBlob = ad.SerializeToBlob();
var ad1 = ActionData.DeserializeFromBlob(actionDataBlob);
不过,我得到当它试图反序列化对象转换为它的类型一个InvalidCastException:
However, I get an InvalidCastException when it tries to cast the deserialized object to its type:
[A] ActionData不能转换为
[b] ActionData。 A型从
起源'XXXX.XXXX.Auditing,版本= 1.0.76.0,
区域性=中性公钥=空'
的背景下,默认在位置
' C:\Users\Craig\AppData\Local\Temp\Temporary
ASP.NET
Files\root\5d978e5b\ffc57fe1\assembly\dl3\2b1e5f8f \102c846e_9506ca01\XXXX.XXXX.Auditing.DLL。
B型从
起源'XXXX.XXXX.Auditing,版本= 1.0.76.0,
区域性=中性公钥=空'在$ B上下文'LoadNeither'
$ b位置'F:\Visual工作室
Projects\XXXXXXXXX\source\XXXX.XXXX.SilverlightClient.Web\bin\XXXX.XXXX.Auditing.dll'。
[A]ActionData cannot be cast to [B]ActionData. Type A originates from 'XXXX.XXXX.Auditing, Version=1.0.76.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\Users\Craig\AppData\Local\Temp\Temporary ASP.NET Files\root\5d978e5b\ffc57fe1\assembly\dl3\2b1e5f8f\102c846e_9506ca01\XXXX.XXXX.Auditing.DLL'. Type B originates from 'XXXX.XXXX.Auditing, Version=1.0.76.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location 'F:\Visual Studio Projects\XXXXXXXXX\source\XXXX.XXXX.SilverlightClient.Web\bin\XXXX.XXXX.Auditing.dll'.
(XXXX.XXXX有掩盖了客户的名字)
(XXXX.XXXX is there to obscure the client's name)
怎么办?
我现在已经问一个相关的问题在这里:
I've now asked a related question here:
的 http://stackoverflow.com/questions/1141873/how-should-i -serialize-一些简单的审计数据换存储-IN-A-SQL表
推荐答案
您已加载相同的程序集的两倍,在不同的装载机上下文一>。例如。你碰巧()首先装载与 Assembly.LoadFrom的XXX.Auditing,然后其他一些(或)集装好正常。事实上,二进制解串器可以装谁大会第二次,虽然我不知道为什么(与ASP.NET没有经验)的人。
You have loaded the same assembly twice, in different loader contexts. E.g. you happened to load the XXX.Auditing with Assembly.LoadFrom()
first, and then some other (or your) assembly loaded it normally. In fact, the binary deserializer could be the one who loaded the assembly a second time, though I wouldn't know why (no experience with ASP.NET).
这篇关于当序列化和InvalidCastException的反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!