ISerializable and backward compatibility

前端 未结 5 1815
我寻月下人不归
我寻月下人不归 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:06

    stmax has an excellent answer, however I would implement it like this, which uses SerializationEntry.GetEnumerator() instead of try/catch. This way is cleaner and significantly faster.

    public MainClass(SerializationInfo info, StreamingContext context) {
        int version = 0;
        foreach (SerializationEntry s in info)
        {
            if (s.Name == "version") 
            {
                version = (int)s.Value;
                break;
            }
        }
    
        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 would prefer a LINQ version using .FirstOrDefault(), but SerializationInfo does not implement IEnumerable - in face, weirdly enough, it doesn't even implement the old IEnumerable interface.

提交回复
热议问题