9

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

4

1 回答 1

14

您忘记替换程序集名称:

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));
    }
}
于 2012-12-19T17:50:45.560 回答