SerializationSurrogate Problem in C#

Started by
3 comments, last by yaroslavd 20 years ago
Hi, guys. I have a problem with saving/loading my objects. I have a Recorder class which has static methods for saving/loading objects of type IRecordable. I also have a nested private class SerializationSurrogate : ISerializationSurrogate. Then, static IFormatter Formatter = new BinaryFormatter(). Then, I assign to its SurrogateSelector property a new SurrogateSelector like this:

SurrogateSelector ss = new SurrogateSelector();
ss.AddSurrogate(typeof(IRecordable),Formatter.Context,new SerializationSurrogate());
Formatter.SurrogateSelector = ss;
I checked that the SerializationSurrogate constructor is called. However, its GetObjectData and SetObjectData methods never get called during Serialization. Can anyone help me with this problem? Lemme know if you want the whole source code. Thanks in advance.
Advertisement
I figured out what the problem is. However, I dunno how to fix it. Basically, when I pass in an object of Character (which implements IRecordable), it looks for the surrogate with the type Character. It ignores the fact that the object is of type IRecordable, also.

Basically, I want this SerializationSurrogate to handle data of any type that implements IRecordable. How can I do this without making a seperate surrogate for each type?

Thanks in advance.
This is how I fixed it:

SurrogateSelector ss = new SurrogateSelector();foreach(Type type in Assembly.GetExecutingAssembly().GetTypes())  if(type.GetInterface("IRecordable")!=null)    ss.AddSurrogate(type,Formatter.Context,new SerializationSurrogate());Formatter.SurrogateSelector = ss;


Is there a better way?

[edited by - yaroslavd on March 23, 2004 9:31:34 PM]
Not that I know of.

If you think about it, it makes perfect sense. Since a class can implement mulitple interfaces - which one should the SurrogateSelector choose if more than one were registured.

Have you tried inheritance instead of an interface pattern?
mdp
You are right, that makes sense. But I have to have IRecordable as an interface because the recordable classes may have to be derived from some other class. The method I described above seems to work fine.

This topic is closed to new replies.

Advertisement