I have an object that is deserialized with this:
public object DeSerializeObject(string filename)
{
object objectToSerialize;
Stream stream = File.Open(filename, FileMode.Open);
BinaryFormatter bFormatter = new BinaryFormatter();
objectToSerialize = (object)bFormatter.Deserialize(stream);
stream.Close();
return objectToSerialize;
}
public GUI_Settings(SerializationInfo info, StreamingContext ctxt)
{
PrinterFont = (Font)info.GetValue("_printFont", typeof(Font));
}
How could I pass in and object as I deserialize it? Kind of like this
public object DeSerializeObject(string filename, someObject thing)
{
......
objectToSerialize = (object)bFormatter.Deserialize(stream, thing);
.....
}
public GUI_Settings(SerializationInfo info, StreamingContext ctxt, someObject thing)
{
PrinterFont = (Font)info.GetValue("_printFont", typeof(Font));
_thing = thing;
}
I’m not quite sure if I explained it clearly let me try again.
Inside of my main class I say
_settings = (GUI_Settings)new ObjectSerializing()
.DeSerializeObject("Settings.data");
or if I understand what Jalal Aldeen Saa’d said
_settings = (GUI_Settings)ObjectSerializing
.DeserializeFromFile<GUI_Settings>("Settings.data");
When the code runs I need to send it a reference to _backend type backEndInitializer. This reference is held within this main class. GUI_Settings is the type that I am deserializing. _backend is the reference that I need to send the GUI_Settings() method to use.
Answer:
public static object DeSerializeObject(string filename, backEndInitializer backend)
{
object state = backend; // your object
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bFormatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(
null,
new System.Runtime.Serialization.StreamingContext(
System.Runtime.Serialization.StreamingContextStates.All,
state)); // pass it in
object objectToSerialize;
Stream stream = File.Open(filename, FileMode.Open);
//BinaryFormatter bFormatter = new BinaryFormatter();
objectToSerialize = (object)bFormatter.Deserialize(stream);
stream.Close();
return objectToSerialize;
}
Then in the class that is being deserialized
public GUI_Settings(SerializationInfo info, StreamingContext ctxt)
{
_backend = (backEndInitializer) ctxt.Context;
}
From there you can access it object in the context argument in your deserialization constructor. The
StreamingContextwill have a reference to this instance