更改类的命名空间后,我无法再反序列化对象。我已经实施了SerializationBinder
。例如:
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();
我得到的例外是:
'System.Runtime.Serialization.TypeLoadExceptionHolder'无法转换为'MyNewNamespace.MyClass'类型
答案 0 :(得分:13)
您忘记更换程序集名称:
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));
}
}