Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

c# - InvalidCastException when serializing and deserializing

I have this code:

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);

However, I get an InvalidCastException when it tries to cast the deserialized object to its type:

[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:UsersCraigAppDataLocalTempTemporary ASP.NET Files oot5d978e5bffc57fe1assemblydl32b1e5f8f102c846e_9506ca01XXXX.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 ProjectsXXXXXXXXXsourceXXXX.XXXX.SilverlightClient.WebinXXXX.XXXX.Auditing.dll'.

(XXXX.XXXX is there to obscure the client's name)

What gives?

I've now asked a related question here:

How should I serialize some simple auditing data for storing in a SQL table?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...