2017-03-08 51 views
2

這裏是我的數組:試圖保存結構文件和加載的文件從一個數組(序列化,反序列化)

Public RacersArray(AmountOfRacers - 1) As Racer 

<Serializable()> Public Structure Racer 
    Public Name As String 
    Public CleatSize As String 
    Public SkillLevel As String 
    Public Height As String 
    Public Team As String 
    Public CompatibilityArr() As String 
End Structure 

<Serializable()> Public Structure Compatibility 
    Public Name As String 
    Public Score As Integer 
End Structure 

下面是我用的,試圖保存和加載從文件中的代碼。該文件得到填充的是一種看上去正確的廢話,而是裝載陣列,它的索引時仍「無」

Public Sub RacersInputSAVE() 
    Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter 
    Dim fStream As New FileStream(SaveLocation, FileMode.Create) 

    bf.Serialize(fStream, InputRacers.RacersArray) ' write to file 

    fStream.Close() 
End Sub 

Public Sub RacersInputLOAD() 
    Dim bf As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter 
    Dim fStream As New FileStream(LoadLocation, FileMode.Open) 

    InputRacers.RacersArray = bf.Deserialize(fStream) ' read from file 

    fStream.Close() 
End Sub 
+0

其實你的代碼應工作原樣。你確定'SaveLocation'和'LoadLocation'指向同一個文件嗎?也許有一個'FileLocation'並將其作爲參數傳遞給你的潛艇會更好。另外考慮嘗試一個使用塊,它更直觀。 – tinstaafl

回答

1

這可能是錯的第一件事情是這樣的:

Public CompatibilityArr() As String 

名稱的基礎上它似乎應該是第二個Compatibility結構。如果是這樣,它應該是:

Public CompatibilityArr As Compatibility() 

其如果是所描述(but when loading the array and it's indexes are still 'nothing'是模糊的,因爲存在多於一個陣列)問題的一部分不清晰。否則,第二個結構不被使用。

Next,set Option Strict On。反序列化時,將BinaryFormatter總是返回Object需要被轉換爲正確的類型:

Racers = DirectCast(bf.Deserialize(fs), Racer()) ' read from file 

有了這些變化2,所有的數據進行的往返對我很好。

第三,Structure是不正確的類型。這些應該是類,而不是公共字段/成員,使用性能尤其是如果有是有約束力的任何涉及的數據:

<Serializable()> 
Public Class Racer 
    Public Property Name As String 
    ... 

而且,任何它實現了Dispose()方法,像FileStream應該在Using使用塊,將關閉與目標對象的處理:

Dim bf As New BinaryFormatter 
Using fs As New FileStream(fileName, FileMode.Create) 
    bf.Serialize(fs, Racers) ' write to file 
End Using 

最後,你可能會發現一些NET的集合,如List(Of Racer)的比陣列更容易與工作。大約需要15分鐘來了解他們的工作方式。

MSDN:Choosing Between Class and Struct

+0

謝謝你們所有的精彩建議!現在一切工作都令人滿意,我無法對你表示感謝。我一定會在將來刷我的列表:) –

+0

列表非常像一個數組,但你不必知道它有多大 - 它們自動增長。爲此:'Racers = DirectCast(bf。反序列化(fs),列表(賽車手))賽車運動員的地方:Dim Racers As List(Racer)這是你需要知道的列表的85% – Plutonix

+0

參見** [五分鐘課程介紹和列表](http://stackoverflow.com/a/34164458)**還添加了一個鏈接到MSDN關於類與結構 – Plutonix

1

出於某種原因,我從未有過的好運氣序列化到使用BinaryFormatter的文件。確切的原因失去了時間的迷霧,但我確實知道,SoapFormatter正常工作對我來說:

Using oStream As Stream = File.Open(SaveLocation, FileMode.Create, IO.FileAccess.Write) 
     If oStream IsNot Nothing Then 
      Call (New System.Runtime.Serialization.Formatters.Soap.SoapFormatter).Serialize(oStream, InputRacers.RacersArray) 
     End If 
    End Using