我尝试用XMLSerializer来序列化VB中的一个类。但是当我为我的类调用GetType时,我得到了一个InvalidOperationException错误。
Dim Playlist_serialize As New XmlSerializer(p.GetType)
这是我的班级:
Public Class Playlist
Private p_name As String
Private p_elements As List(Of Playlist_element)
Sub New()
p_elements = New List(Of Playlist_element)
End Sub
Public Property Name() As String
Get
Name = p_name
End Get
Set(value As String)
p_name = value
End Set
End Property
Public Property Elements() As List(Of Playlist_element)
Get
Elements = p_elements
End Get
Set(value As List(Of Playlist_element))
p_elements = value
End Set
End Property这是我的Playlist_element:
Public Class Playlist_element
Private p_Name As String
Private p_Type As String
Private p_Genre As String
Public Property Name() As String
Get
Name = p_Name
End Get
Set(value As String)
p_Name = value
End Set
End Property
Public Property Type() As String
Get
Type = p_Type
End Get
Set(value As String)
p_Type = value
End Set
End Property
Public Property Genre() As String
Get
Genre = p_Genre
End Get
Set(value As String)
p_Genre = value
End Set
End Property
Sub New(ByVal name As String, ByVal type As String, ByVal genre As String)
Me.Name = name
Me.Genre = genre
Me.Type = Type
End Sub
End Class发布于 2015-01-17 15:26:11
Playlist_element的编码方式有几个问题。首先,属性获取器是错误的。他们需要返回支持字段:
Public Property Name() As String
Get
' this does nothing:
'Name = p_Name
Return p_Name
End Get
Set(value As String)
p_Name = value
End Set
End Property接下来,即使可以,我也不会使用Type作为属性名。如果您钻研内部异常并查看消息,它会告诉您,它不能序列化PlayList_element,因为它没有简单的构造函数。所有序列化程序都需要这样做,因为它们不知道如何使用:
Sub New(ByVal name As String, ByVal type As String, ByVal genre As String)
p_Name = name
p_Genre = genre
p_Type = type
End Sub
' add:
Public Sub New()
End Sub它应该能正常工作。我应该注意到,从VS2010开始,您可以使用自动实现的属性并跳过许多代码:
Public Class Element
Public Property Name() As String
Public Property Type() As String
Public Property Genre() As String
Sub New(name As String, type As String, genre As String)
_Name = name
_Genre = genre
_Type = type
End Sub
Public Sub New()
End Sub
End ClassVS提供了一个“隐藏”支持字段,如_Name、_Genre等。
https://stackoverflow.com/questions/28000316
复制相似问题