我試圖保存對象的列表以保存文件,但得到過程中拋出的異常。這是我的對象類:嘗試序列化對象列表失敗
<Serializable()>
Public Class FavoritesObject
Private Dset As DataSet
Private Name As String
Private BSource1 As BindingSource
Private Bsource2 As BindingSource
Public Sub New()
' Leave fields empty.
End Sub
Public Sub New(ByVal datset As DataSet, ByVal thename As String, ByVal binsource1 As BindingSource, ByVal binsource2 As BindingSource)
Dset = datset
Name = thename
BSource1 = binsource1
binsource2 = binsource2
End Sub
Public Property Dataset1 As DataSet
Get
Return Dset
End Get
Set(ByVal value As DataSet)
Dset = value
End Set
End Property
Public Property FavoriteName As String
Get
Return Name
End Get
Set(ByVal value As String)
Name = value
End Set
End Property
Public Property BindingSource1 As BindingSource
Get
Return BSource1
End Get
Set(ByVal value As BindingSource)
BSource1 = value
End Set
End Property
Public Property BindingSource2 As BindingSource
Get
Return Bsource2
End Get
Set(ByVal value As BindingSource)
Bsource2 = value
End Set
End Property
End Class
這裏是我的序列化和反序列化功能:
Public Sub WriteToBinaryFile(serializationFile As String, List As List(Of FavoritesObject))
Using stream As Stream = File.Open(serializationFile, FileMode.Create)
Dim bformatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bformatter.Serialize(stream, List)
End Using
End Sub
Public Function ReadFromBinaryFile(serializationFile As String)
Using stream As Stream = File.Open(serializationFile, FileMode.Open)
Dim bformatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim favorites As List(Of FavoritesObject) = DirectCast(bformatter.Deserialize(stream), List(Of FavoritesObject))
Return favorites
End Using
End Function
當我試圖序列我的對象列表我得到下面的異常拋出:
在mscorlib.dll中發生類型爲'System.Runtime.Serialization.SerializationException'的未處理異常 附加信息:在「組件」系統中鍵入'System.Windows.Forms.BindingSource'。 Windows.Forms,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089'未標記爲可序列化。
我真的不熟悉序列化,並試圖學習它。有人可以澄清一下我的問題可能是什麼以及可能的解決辦法嗎?
不從異常消息'BindingSource'不應該(也不能)被序列化是明顯 –
答案下面給出了直接的技術解決方案。更大的問題是你的設計,一個域實體不應該包含UI或持久性代碼。 –
@HenkHolterman沒有意識到這一點,謝謝。事後看來,沒有理由將它們儲存起來,因爲它們可以在飛行中創建。 –