在更改类的名称空间后,无法使用binaryFormatter反序列化

时间:2012-10-04 23:48:23

标签: c# deserialization

更改类的命名空间后,我无法再反序列化对象。我已经实施了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'类型

1 个答案:

答案 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));
    }
}