您的位置:首页 > 移动开发 > Unity3D

不同Assembly中使用 BinaryFormatter 序列化的问题

2015-11-10 17:22 447 查看
Unity游戏项目.在PVE验证时.将验证信息序列化.发送到服务器端.在服务器端反序列化.并进行验证.为了共享结构.使用同一份代码.在服务器端使用了中间语言.直接调用C#代码.

序列化过程为方便使用了 BinaryFormatter

反序列化时遇到问题.在反序列化结构时抛出异常

An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll

google下来的理解为 BinaryFormatter 存储类型信息时存储了当前集合的类型信息.这样导致序列化出来的信息只能在同一个程序集内使用.

好在提供了可以重写的SerializationBinder

<span style="font-size:18px;">	class BindChanger : System.Runtime.Serialization.SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
// Define the new type to bind to
Type typeToDeserialize = null;

// Get the assembly names
string currentAssembly = Assembly.GetExecutingAssembly().FullName;

// Create the new type and return it
typeToDeserialize = Type.GetType(string.Format("{0}, {1}", typeName, currentAssembly));
return typeToDeserialize;
}
}</span>


使用时指定
<span style="font-size:18px;">		BinaryFormatter bin = new BinaryFormatter();
bin.Binder = new BindChanger();</span>


然而在序列化容器时会遇到
unable to load type system.collections.generic.list`1 的异常.

没能找到解决方案.看来需要自己序列化容器.

算了.还是换个序列化方式吧..

参考
https://www.daniweb.com/programming/software-development/threads/339638/deserializing-in-a-different-assembly http://stackoverflow.com/questions/14990980/system-runtime-serialization-serializationexception-unable-to-find-assembly-mya http://spazzarama.com/2009/06/25/binary-deserialize-unable-to-find-assembly/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Unity 序列化