我正在制作“机器人大战”类型的代码,用户可以在其中创建,删除和搜索角色及其统计数据。当我创建一个角色时,我希望即使在程序关闭后也能够使用该角色。有没有办法做到这一点?我现在正在声明私有子数组中的数组:
Dim characters(10,4) As String
'name , attack , defense , health
Private Sub ExtractInfo()
characters(1, 1) = "Terminus"
characters(1, 2) = "72"
characters(1, 3) = "14"
characters(1, 4) = "200"
characters(2, 1) = "Sir Kill-a-lot"
characters(2, 2) = "60"
characters(2, 3) = "30"
characters(2, 4) = "250"
但是,我希望即使代码停止运行,也可以保存此处的信息和添加的信息以供使用。
答案 0 :(得分:2)
保存/加载二进制数据的一种方法是使用Serialization
很容易实现非复杂的对象关系。
所以基本上你创建一个类并用<Serializable>
属性来装饰它。
当您调用正确的BinaryFormatter.Serialize
或BinaryFormatter.Deserialize
方法时,所有(公共)成员将被序列化/反序列化。
示例:
<Serializable>
Public Class Characters
Public characters(10, 4) As String
Public Sub Save(path As String)
serialize(path)
End Sub
Public Shared Function Load(path As String) As Characters
Return deSerialize(path)
End Function
Private Sub serialize(path As String)
Try
Using fs As Stream = New FileStream(path, FileMode.OpenOrCreate)
Dim bf As New BinaryFormatter
bf.Serialize(fs, Me)
End Using
Catch ex As Exception
'Error handling
End Try
End Sub
Private Shared Function deSerialize(path As String) As Characters
Try
Using fs As Stream = New FileStream(path, FileMode.OpenOrCreate)
Dim bf As New BinaryFormatter
deSerialize = CType(bf.Deserialize(fs), Characters)
End Using
Return deSerialize
Catch ex As Exception
'Error handling
End Try
End Function
End Class
用法:
Sub Main()
Dim a = New Characters()
a.characters(0, 0) = "Stack"
a.characters(0, 1) = "Overflow"
a.characters(1, 0) = "Is"
a.characters(1, 1) = "awesome!"
a.Save("E:\characters.sav")
Dim b = Characters.Load("E:\characters.sav")
Console.WriteLine(b.characters(0, 0))
'-> Stack
Console.ReadLine()
End Sub