Deserialize to self

  • Thread starter Thread starter George Addison
  • Start date Start date
G

George Addison

I understand this might not be the optimal method of
deserialization, but how can I deserialize a class to
itself? Something like:

Public Sub New(Optional ByVal filename as string =
Nothing)
If Not IsNothing(filename) then
fs = New System.IO.FileStream(filename,
System.IO.FileMode.Open)
Dim sf As New
System.Runtime.Serialization.Formatters.Soap.SoapFormatter
me = CType(sf.Deserialize(fs), cJob)
End If
End Sub
 
How about creating a shared method called "Load" or something that returns
the deserialized instance?

Alternatively, but messy, you could deserialize to a local variable instance
and then copy all its fields to the current instance.

Hope this helps,

Trev.
 
* "George Addison said:
I understand this might not be the optimal method of
deserialization, but how can I deserialize a class to
itself? Something like:

Public Sub New(Optional ByVal filename as string =
Nothing)
If Not IsNothing(filename) then
fs = New System.IO.FileStream(filename,
System.IO.FileMode.Open)
Dim sf As New
System.Runtime.Serialization.Formatters.Soap.SoapFormatter
me = CType(sf.Deserialize(fs), cJob)
End If
End Sub

You cannot assign anything to 'Me'. I would create a shared method in
the class which returns an instance of the class.
 
George,
Short answer: You Don't!!!!

Long answer: You cannot deserialize a class to "me" as by the time the
constructor executes the object has already been created. Deserialization
creates a new object!

A couple of alternatives would be to add a Factory Method to your class that
deserializes an instance of the class and return it.

Public Class cJob

Private m_attr1 As String
Private m_attr2 As String
Public Shared Function FromFile(ByVal filename as string) As cJob
fs = New System.IO.FileStream(filename,
System.IO.FileMode.Open)
Dim sf As New
System.Runtime.Serialization.Formatters.Soap.SoapFormatter
return DirectCast(sf.Deserialize(fs), cJob)
End

End Class

Note that the above Factory Method is a Shared method (you do not need an
instance of the class to use it) and it returns an instance of the class.

A more involved alternative is to have a class private to cJob that contains
all of cJOb's data, then each method of cJob would delegate to this private
class

Public Class Job

Private Class JobData
Private m_attr1 As String
Private m_attr2 As String
End Class

Private Readonly m_data As JobData

Public Sub New()
m_data = new JobData
End Sub

Public Sub New(ByVal filename as string)
fs = New System.IO.FileStream(filename,
System.IO.FileMode.Open)
Dim sf As New
System.Runtime.Serialization.Formatters.Soap.SoapFormatter
m_data = DirectCast(sf.Deserialize(fs), JobData)
End

End Class

Of course this runs into problems when you attempt to serialize, as you
cannot really serialize the Job object, you need to serialize the JobData
object. I would favor the Factory Method.

Hope this helps
Jay
 
Back
Top