无法在VB.NET中的可序列化单例类实例上调用Serialize()

时间:2011-11-28 04:09:43

标签: .net vb.net serialization

我有一个实现Serializable的VB.NET单例类:

Imports System.IO
Imports System.Runtime.Serialization

<Serializable()> Public Class CoordinateHistory
    Private Shared _thisInstance As CoordinateHistory

    Private gpsHistory As Dictionary(Of DateTime, GpsTimeCoordinate)
    Private gpsTimes As List(Of DateTime)

    Public Event NewStatusInformation(statusInfo As String)

    Protected Sub New()
        gpsHistory = New Dictionary(Of DateTime, GpsTimeCoordinate)
        gpsTimes = New List(Of DateTime)
    End Sub

    Public Shared Function getInstance() As CoordinateHistory
        If _thisInstance Is Nothing Then
            _thisInstance = New CoordinateHistory
        End If

        Return _thisInstance
    End Function

    Public Function getHistoryCount() As Integer
        Return gpsHistory.Count
    End Function

    ' bunch of other class functions below...
End Class

我的问题是我实际上无法在此类的实例上调用.Serialize(),就像在线显示的所有示例一样。我究竟做错了什么?谢谢!

2 个答案:

答案 0 :(得分:3)

我认为问题是您的受保护子。如果将其更改为“公共”,则可以正确序列化。

<强>更新

使用BinaryFormatter序列化默认实例时没有任何问题:

Dim abData As Byte()

Using oStream As New MemoryStream
    Call (New BinaryFormatter).Serialize(oStream, CoordinateHistory.getInstance())

    abData = oStream.ToArray()
End Using

或XMLFormatter:

Dim sData As String

Using oStream As New MemoryStream
    Dim oSerializer As New XmlSerializer(CoordinateHistory.getInstance().GetType)

    oSerializer.Serialize(oStream, CoordinateHistory.getInstance())

    sData = Encoding.Default.GetString(oStream.ToArray())
End Using

也许这是您正在使用的序列化框架?

答案 1 :(得分:2)

问题可能是您的班级公共活动。有一篇文章here描述了使用事件序列化VB.NET类以及如何解决它们的问题。

修改:另请参阅此可能相关的question