Hello Folks
I am trying to create an xml file from a class containing a
polymorphic array. The example: AutoCompany contains an array of
Vehicles(base class) which can either be Cars or Trucks(derived classes).
Everything works accept the XMLSerialization. The error is very vague. The
simplified code follows and the entire code can be downloaded from a
compressed file from
http://www.Cartner.Net/PolymorphismExample.zip
Please let me know what is causing this. I have not found any
examples on the internet that address this specific problem. Thank you for
your help in advance.
Best Regards
Todd
-------------------------------------------------------------------
Option Explicit On
Option Strict On
Imports System.IO
Imports System.Xml.Serialization
Public Class frmMain
Inherits System.Windows.Forms.Form
Private GeneralMotors As clsAutoCompany
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
GeneralMotors.ToString()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim XSer As XmlSerializer = New XmlSerializer(GetType(clsAutoCompany))
Dim FIO As TextWriter = New StreamWriter("PolyTest.xml")
' ********** Error occurs on the next line **********
XSer.Serialize(FIO, Me.GeneralMotors)
FIO.Close()
End Sub
End Class
-------------------------------------------------------------------
Option Explicit On
Option Strict On
<Serializable()> Public Class clsAutoCompany
Public Vehicles() As clsVehicle
Public Sub New()
Dim VT As clsTruck
Dim VC As clsCar
ReDim Vehicles(3)
VT = New clsTruck
VT.Index = 0
VT.TruckType = "SUV"
Vehicles(0) = VT
VC = New clsCar
VC.Index = 1
VC.CarType = "Sports"
Vehicles(1) = VC
VC = New clsCar
VC.Index = 2
VC.CarType = "Luxury"
Vehicles(2) = VC
VT = New clsTruck
VT.Index = 3
VT.TruckType = "4X4"
Vehicles(3) = VT
End Sub
Public Overrides Function ToString() As String
Dim Counter As Int32
For Counter = 0 To Vehicles.Length - 1
Debug.WriteLine(Vehicles(Counter).ToString & " - " &
Vehicles(Counter).Index.ToString)
Next
End Function
End Class
-------------------------------------------------------------------
Option Explicit On
Option Strict On
<Serializable()> Public MustInherit Class clsVehicle
Public Index As Int32
Public Sub New()
Index = -1
End Sub
Public MustOverride Shadows Function ToString() As String
End Class
<Serializable()> Public Class clsCar
Inherits clsVehicle
Public CarType As String
Public Overrides Function ToString() As String
Dim Output As String
Output = "Car Type = " & CarType
Return Output
End Function
End Class
<Serializable()> Public Class clsTruck
Inherits clsVehicle
Public TruckType As String
Public Overrides Function ToString() As String
Dim Output As String
Output = "Truck Type = " & TruckType
Return Output
End Function
End Class
-------------------------------------------------------------------
Best Regards
Todd