我想创建一个序列化指定为参数的LIST的过程。但是当我通过参数解析MyClass时,我无法弄清楚如何指定 GetType(List(of MyClass))。我不能"硬编码"我在程序中的MyClass必须使用不同类的序列化程序。
Sub Main
Dim MyList As New List(Of NameClass)
MyList.Add(New NameClass("Thomas")
MyList.Add(New NameClass("Michael")
List_To_XMLFile(MyList, NameClass, "c:\temp\file.xml")
End sub
Sub List_To_XMLFile(MyList As List(Of Object), ListOfCObj As Object, Path As String)
Dim ser As XmlSerializer = New XmlSerializer(GetType(List(Of ListOfObject)))
Dim fs As FileStream = New FileStream(Path, FileMode.Create)
ser.Serialize(fs, MyList)
fs.Close()
End Sub
Public Class NameClass
Property Name As String
Sub New()
End Sub
Sub New(Name As String)
Me.Name = Name
End Sub
End Class
答案 0 :(得分:1)
对象知道它的类型,因此如果传递对象,则不需要传递类型。
Sub List_To_XMLFile(Of T)(MyList As List(Of T), Path As String)
Dim ser As XmlSerializer = New XmlSerializer(MyList.GetType())
Dim fs As FileStream = New FileStream(Path, FileMode.Create)
ser.Serialize(fs, MyList)
fs.Close()
End Sub
使用
调用该过程List_To_XMLFile(MyList, "c:\temp\file.xml")
请注意,由于我使用的是泛型类型,因此可以将该方法称为传递New List(Of NameClass)
,New List(Of OtherClass)
等。以便T
采用该类型。