Is it possible to de-serialize a new Derived class using Old Binary?

In my project, I have a class that I serialize in binary to disk.

Due to some new requirement, I need to create a new class that is derived from the original class.

eg,

[Serializable]
public class Sample
{
    String someString;
    int someInt;

    public Sample()
    {
    }

    public Sample(String _someString, int _someInt)
    {
        this.someInt = _someInt;
        this.someString = _someString;
    }

    public String SomeString
    {
        get { return someString; }
    }

    public int SomeInt
    {
        get { return someInt; }
    }
}

[Serializable]
public class DerivedSample : Sample
{
    String someMoreString;
    int someMoreInt;

    public DerivedSample ()
        : base()
    {
    }

    public DerivedSample (String _someString, int _someInt, String _someMoreString, int _someMoreInt)
        :
        base(_someString, _someInt)
    {
        this.someMoreString = _someMoreString;
        this.someMoreInt = _someMoreInt;
    }
    public String SomeMoreString
    {
        get { return someMoreString; }
    }

    public int SomeMoreInt
    {
        get { return someMoreInt; }
    }
}

When I try to serialize an old file that contains only a Sample object, it works fine in the current assembly. This means that backward compatibility exists. But when I try to deserialize the file containing the DerivedSample object using the previous version of the build application, it fails. This means that you must take care before starting compatibility ...

Is it possible to read only part of the base class of an object from a new version of a file?

+3
4

, DerivedSample , , - , DerivedSample, Sample.

, , , (DerivedSample), - .

, -, , , . Sample, , . ( ), ( ): http://msdn.microsoft.com/en-us/library/ms229752(VS.80).aspx

?

+2

? BinaryFormatter , , - protobuf-net, ; , , .

, xml; XmlSerializer, DataContractSerializer .. IMO, BinaryFormatter -, .

, / ; , BinaryFormatter .

+2

?

Sample, DerivedSample, . , , .

, WCF . DataContracts , / .

-Doug

0

You need to use the so-called serialization surrogate. You can inject it into a binary serializer, and then, at run time, the surrogate can replace serialized / deserialized for your own type. I used it in the past when the type was moved between assemblies and the code could no longer deserialize old files. More about surrogates here: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.surrogateselector(v=VS.100).aspx

0
source

Source: https://habr.com/ru/post/1745122/


All Articles