反序列化异常:无法找到程序集 [英] Deserialization exception: Unable to find assembly

查看:175
本文介绍了反序列化异常:无法找到程序集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在序列化字段和自定义类之类的一些数据以创建二进制数据(字节数组)。



然后我要 Deserialize 从二进制数据返回到字段和类。



但是我遇到了一个例外。如果这两种方法将在同一程序集中进行,则一切正常,但事实并非如此。



我一次巧妙地进行序列化,而另一次进行反序列化。也是这样说:
无法找到程序集'MyAssamblyName,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'。



注1:取回字段没有问题,只有类引起它们。



注意2:我在两个程序集中都有相同的类。

解决方案

<注意2:我在两个程序集中都有相同的类


不,您没有。至少,就运行时间而言。您有两种碰巧具有相同名称的不同类型。类型由其组装定义。因此,即使Assembly.B中的 SomeType 在AssemblyB中与 SomeType 完全不同



BinaryFormatter可以处理类型信息,因此无法使用。一种选择是将类型移动到两个其他项目都引用的库dll中-然后仅定义一次,这将很高兴。



另一种选择是与基于合同的序列化器(而不是基于类型的序列化器)一起使用。这意味着即使它们位于不同的程序集中(即使它们具有足够相似的条件,也可能具有不同的来源),看起来足够相似的类还是可以的。适用于此的序列化器的示例包括(以及其他一些)XmlSerializer,DataContractSerializer(但不包括NetDataContractSerializer),JavaScriptSerializer或protobuf-net(如果您想要密集的原始二进制文件)。


I'm serializing some data like fields and custom class to create a binary data (byte array).

Then I want to Deserialize it back from binary data to fields and class.

But I get an exception. It would all work fine if these two methods would happen in same assembly - but its not.

I do Serialization in one assambly, and do the Deserialization in another one. And this is the excaption saying too: Unable to find assembly 'MyAssamblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

NOTE 1: I have no issues with getting the fields back, only the classes causes them.

NOTE 2: I have this same class in both assemblies.

解决方案

NOTE 2: I have this same class in both assemblies

No you don't. At least, not as far as the runtime is concerned. You have two different types that happen to have the same name. A type is defined by its assembly. Thus "SomeType in AssemblyA" is completely different to "SomeType in AssemblyB", even if they happen to have been compiled from the same source file.

BinaryFormatter works with type information, so this won't work. One option would be to move the type to a library dll that both the other projects reference - then it is only defined once, and it will be happy.

Another option is to work with a contract-based serializer (rather than a type-based serializer). This means that "classes that look similar enough" are fine, even if they are in different assemblies (and perhaps have different source, as long as it is "similar enough"). Examples of suitable serializers for this would include (plus a few others) XmlSerializer, DataContractSerializer (but not NetDataContractSerializer), JavaScriptSerializer, or protobuf-net if you want dense raw binary.

这篇关于反序列化异常:无法找到程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆