[英]InvalidOperationException on GetType
I try to serialize a Class in VB using XMLSerializer. 我尝试使用XMLSerializer在VB中序列化一个类。 But when I call GetType for my Class I got a InvalidOperationException error. 但是,当我为类调用GetType时,出现了InvalidOperationException错误。
Dim Playlist_serialize As New XmlSerializer(p.GetType)
Here is my class : 这是我的课:
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
Here is my Playlist_element : 这是我的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
There are several issues with the way Playlist_element
is coded. Playlist_element
的编码方式存在几个问题。 First your property getters are wrong. 首先,您的财产获取者是错误的。 They need to return the backing field: 他们需要返回支持字段:
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
Next, I would not use Type
as a property name even if you can. 接下来,即使可以,我也不会使用Type
作为属性名称。 If you drill into the inner exception and view the message, it tells you that it cannot serialize PlayList_element
because it does not have a simple constructor. 如果您深入研究内部异常并查看消息,它会告知您无法序列化PlayList_element
因为它没有简单的构造函数。 All serializers require this because they do not know how to use: 所有串行器都需要这样做,因为它们不知道如何使用:
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
It should work fine. 它应该工作正常。 I should note that as of VS2010, you can use auto-implemented properties and skip a lot of that code: 我应该注意,从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 Class
VS provides a "hidden" backing field as with _Name
, _Genre
etc. VS提供了一个“隐藏的”后备字段与_Name
, _Genre
等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.