首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >InvalidOperationException on GetType

InvalidOperationException on GetType
EN

Stack Overflow用户
提问于 2015-01-17 14:11:53
回答 1查看 96关注 0票数 1

我尝试用XMLSerializer来序列化VB中的一个类。但是当我为我的类调用GetType时,我得到了一个InvalidOperationException错误。

Dim Playlist_serialize As New XmlSerializer(p.GetType)

这是我的班级:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-17 15:26:11

Playlist_element的编码方式有几个问题。首先,属性获取器是错误的。他们需要返回支持字段:

代码语言:javascript
复制
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,因为它没有简单的构造函数。所有序列化程序都需要这样做,因为它们不知道如何使用:

代码语言:javascript
复制
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开始,您可以使用自动实现的属性并跳过许多代码:

代码语言:javascript
复制
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提供了一个“隐藏”支持字段,如_Name_Genre等。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28000316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档