Getting a Type of Me
-
I have several classes in my project that I need to persist as XML. I achieved this by using serialization - I have load/save function in each class. Since I'm using the same routines in each class, it makes more sense to me to create a class with these routines in it, and then derive each class from this one. With me so far? So, here is my base class (which the other classes will derive from): Imports System.IO Imports System.Xml.Serialization Public MustInherit Class XMLSerializationBase Public Sub SavetoXML(ByVal Filename As String) Dim writer As StreamWriter = Nothing Try Dim ser As XmlSerializer = New XmlSerializer(Me.GetType) writer = New StreamWriter(Filename) ser.Serialize(writer, Me) Catch ex As Exception Dim strErr As String = String.Format("Unable to save file. Error: ", ex.Message) MessageBox.Show(strErr, "File Save Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Finally If Not writer Is Nothing Then writer.Close() writer = Nothing End Try End Sub Public Function LoadfromXML(ByVal filename As String) Dim reader As StreamReader = Nothing Try Dim ser As XmlSerializer = New XmlSerializer(Me.GetType) reader = New StreamReader(filename) Dim o = CType(ser.Deserialize(reader), XMLSerializationBase) '<------ HERE IS THE PROBLEM If o Is Nothing Then Throw New NullReferenceException("Invalid file") Return o Catch ex As Exception Dim strErr As String = String.Format("Unable to load file. Error: ", ex.Message) MessageBox.Show(strErr, "File Open Error", MessageBoxButtons.OK, MessageBoxIcon.Error) Finally If Not reader Is Nothing Then reader.Close() reader = Nothing End Try End Function End Class Ok, so here is the problem When I deserialize the info, I need to convert it into a type of class - whatever type of class the base class is. So what I really want to do is this: Dim o = CType(ser.Deserialize(reader), Me) The problem is, this doesn't work - the IDE won't accept it. I also tried MyBase, Me.GetType, MyBase.GetType - none of these work, the IDE says that the object is not defined, or that it is an invalid type. How to I tell CType to convert the info to whatever type of class my base class is??? -Todd Davis (toddhd@gmail.com)