简体   繁体   中英

Serializing and deserializing an object as an ID

Sorry if the title is a bit confusing, but I couldn't think of a better one.

The idea is that I have a central object repository that can fetch objects by IDs, and these objects should not be serialized. But there are several references to the objects, which should be serialized, but only as an ID, and then deserialized from an ID using the repository.

So I thought of implementing the ISerializable interface for my object, so that it stores the ID in GetObjectData , and so that it restores the object from ID when deserializing. The problem is that deserializing is done in the constructor, so I can't return an existing object... How would I go around this? Or maybe other suggestions on how to do this?

Edit - seems to be unclear, so I'll try to clarify.

public class Ref {
    MyObj obj;
}

public class MyObj {
    string id;
    string objData;

    public static MyObj GetObj(string id) {
        // reads MyObj from a file or web service based on ID
        // caches objects as well
    }    
}

Now, in my program, I have several instances of Ref , which reference different MyObj s. I want to serialize these Ref objects, without actually serializing MyObj , but instead I'd like to serialize only the ID, which I can later use to fetch the object when deserializing.

I'd hope to do something like this:

[Serializable]
public class MyObj : ISerializable {
// code from before ...

public MyObj (SerializationInfo info, StreamingContext ctxt) {
        return MyObj.GetObj(info.GetString("id")); // this is not possible since this is a constructor and not a factory!
}

public void GetObjectData(SerializationInfo info, StreamingContext ctxt) {
    info.AddValue("id", this.id);
}    

}

Here's an idea. Create a wrapper class, named ObjectHolder for example. Your other classes can reference this ObjectHolder, and this ObjectHolder references the actual objects in the repository. Override the serialization and deserialization logic of the ObjectHolder class. You will have many ObjectHolder references, instead of many copies of the same objects.

Here's another one. It works if you don't have too many classes. Store the object reference ID in a private field. Write a getter property that fetches the object from the repository. This way only the ID will ever be serialized and the object will always be fetched on the fly. Like this:

private string id; // serialized
public Whatever MyObject { // not serializer
    get { return Repository.Get(id); }
}

You see, if you go this way, you have to change your references in many places. With the ObjectHolder class, it gets a bit more simple because the object fetching logic is implemented in only one place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM