ISerializable: Assign an existing object during deserialization

Our task is quite simple: we have an object graph where each object (IDItem) has a unique identifier. The graph of objects exists twice, on the client and on the server.

Now we send some serializable commands to the server. The command has some IDItems as fields. IDItems implement the ISerializable interface and store only their identifier in SerializationInfo. How:

// The method called when serializing a IDItem.
void GetObjectData(SerializationInfo info, StreamingContext context)
{
    // Instead of serializing this object, just save the ID
    info.AddValue("ID", this.GetID());
}

The problem is, how can we assign an existing object to the instance created by the deserializer? Obviously, something like the following in the ISerializable constructor does not work, because the identifier 'this' is read-only:

//does not work   
protected IDItem(SerializationInfo info, StreamingContext context)
{
    this = GlobalObject.GetIDItem(info.GetString("ID"));
}

So, any idea how we can Assign an existing object to a deserialized object?

Best regards, thalm

+3
2

, , -, IObjectReference .

( - , , , .. .)

[Serializable]
public class Example : ISerializable
{
    // ...

    void ISerializable.GetObjectData(
        SerializationInfo info, StreamingContext context)
    {
        info.SetType(typeof(ExampleDeserializationProxy));
        info.AddValue("ID", this.GetID());
    }
}

// ...

[Serializable]
public class ExampleDeserializationProxy : IObjectReference, ISerializable
{
    private readonly int _id;

    private ExampleDeserializationProxy(
        SerializationInfo info, StreamingContext context)
    {
        _id = info.GetInt32("ID");
    }

    object IObjectReference.GetRealObject(StreamingContext context)
    {
        return GlobalObject.GetIDItem(_id);
    }

    void ISerializable.GetObjectData(
        SerializationInfo info, StreamingContext context)
    {
        throw new NotSupportedException("Don't serialize me!");
    }
}
+5

.

, , / ? , . , , .

- , , , , .

+1

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


All Articles