ISerializable and backward compatibility

前端 未结 5 1823
我寻月下人不归
我寻月下人不归 2021-01-05 14:30

I have to work an an old application that used binaryFormatter to serialize application data into filestream (say in a file named \"data.oldformat\") without any optimizazio

5条回答
  •  天涯浪人
    2021-01-05 15:25

    since you've already implemented the ISerializable interface, you've probably also already added the required constructor:

    public MainClass(SerializationInfo info, StreamingContext context) {}
    

    you can use the info-object passed to the constructor to retrieve data from the serialized file. by default (i.e. when no ISerializable is implemented), the fields names are used as identifiers during serialization. so if your old class had a field "int x" you can deserialize this using:

    this.x = info.GetInt32("x");
    

    for newer versions i normally add a "version" entry during serialization, like this:

    public void GetObjectData(SerializationInfo info, StreamingContext context) {
      info.AddValue("version", 1);
      info.AddValue("othervalues", ...);
    }
    

    during deserialization you can check this version entry and deserialize accordingly:

    public MainClass(SerializationInfo info, StreamingContext context) {
        int version;
        try {
           version = info.GetInt32("version");
        }
        catch {
           version = 0;
        }
    
        switch (version) {
          case 0:
            // deserialize "old format"
            break;
          case 1:
            // deserialize "new format, version 1"
            break;
          default:
            throw new NotSupportedException("version " + version + " is not supported.");
        }
    }
    

    i haven't compiled that code, might contain typos.

    hope that helps.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题