改变类的命名空间后不能用的BinaryFormatter反序列化 [英] Can't deserialize with binaryFormatter after changing namespace of class
本文介绍了改变类的命名空间后不能用的BinaryFormatter反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
改变我的类的命名空间后,我再也不能反序列化对象。我实现了 SerializationBinder
。例如:
公共类TypeNameConverter:SerializationBinder
{
公众覆盖类型BindToType(字符串的AssemblyName,字符串的typeName )
{
的typeName = typeName.Replace(MyOldNamespace,MyNewNamespace);
返回Type.GetType(的String.Format({0},{1}的typeName,的AssemblyName));
}
}
BinaryFormatter的BF =新的BinaryFormatter();
bf.Binder =新TypeNameConverter();
我得到的例外是:
System.Runtime.Serialization.TypeLoadExceptionHolder'不能转换为类型MyNewNamespace.MyClass
块引用>
解决方案您忘了更换该组件名称:
类TypeNameConverter:SerializationBinder
{
公众覆盖类型BindToType(字符串的AssemblyName,字符串的typeName)
{
的typeName = typeName.Replace(MyOldNamespace,MyNewNamespace);
的AssemblyName = assemblyName.Replace(MyOldNamespace,MyNewNamespace);
返回Type.GetType(的String.Format({0},{1}的typeName,的AssemblyName));
}
}
After changing the namespace of my class I can no longer deserialize the objects. I've implemented
SerializationBinder
. Example:public class TypeNameConverter : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { typeName = typeName.Replace("MyOldNamespace", "MyNewNamespace"); return Type.GetType(string.Format("{0}, {1}", typeName, assemblyName)); } } BinaryFormatter bf = new BinaryFormatter(); bf.Binder = new TypeNameConverter();
The exception I get is:
'System.Runtime.Serialization.TypeLoadExceptionHolder' cannot be converted to type 'MyNewNamespace.MyClass'
解决方案you forgot to replace the assembly name:
class TypeNameConverter : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { typeName = typeName.Replace("MyOldNamespace", "MyNewNamespace"); assemblyName = assemblyName.Replace("MyOldNamespace", "MyNewNamespace"); return Type.GetType(string.Format("{0}, {1}", typeName, assemblyName)); } }
这篇关于改变类的命名空间后不能用的BinaryFormatter反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文