是否有可能恢复经由&QUOT序列化对象; BinaryFormatter的"变化的类名之后?有可能、对象、序列化、BinaryFormatter

2023-09-02 21:40:09 作者:七个字

我用的BinaryFormatter 来存储我的应用程序设置。如今,数年后继续发展,很多用户已经在使用我的应用程序后,我想更改几个类的命名和命名空间是什么,他们的位置。但是,如果我这样做,它不再是可能加载的设置,因为 BinaryFormater 由他们IN-code的名字叫事。

I was using BinaryFormatter to store my application settings. Now, several years into continued development, after many users are already using my application, I want to change how several classes are named and in what namespaces they are located. However, if I do that, it is no longer possible to load the settings, because BinaryFormater calls things by their in-code names.

因此​​,举例来说,如果我改变 MyNamespace.ClassOne MyNamespace.Class.NumberOne 在code,我不能再加载设置,因为 MyNamespace.ClassOne 已不存在。

So, for example, if I change MyNamespace.ClassOne to MyNamespace.Class.NumberOne in code, I can no longer load the settings, because MyNamespace.ClassOne no longer exists.

我想两者进行更改,并允许用户保留其设置文件。这可能吗?

I'd like to both make this change and allow users retain their settings files. Is this possible?

我的意思是,我想我可以研究它的保存格式,并手动修改二进制文件,类名替代,但是这将是黑客的做法。必须有一个正常的做法,对吗?

I mean, I guess I can study the format it's saved in, and manually alter the binary file, substituting class names, but that would be hacker's approach. There must be a normal approach to this, right?

推荐答案

是的,这是可能的。您可以使用 SerializationBinder 类。事情是这样的:

Yes, it is possible. You can use the SerializationBinder class. Something like this:

public class ClassOneToNumberOneBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        typeName = typeName.Replace(
            "MyNamespace.ClassOne",
            "MyNamespace.Class.NumberOne");

        assemblyName = assemblyName.Replace("MyNamespace", "MyNamespace.Class");

        return Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
    }
}

BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Binder = new ClassOneToNumberOneBinder();

从适应了这个答案

code的例子。

Code example adapted from this answer.