下記はVB2005のコードです。
Public Structure IDATA
Public Data1 As Integer
Public Data2 As Integer
Public Data3 As Integer
End Structure
Dim abc As IDATA
My.Computer.FileSystem.WriteAllBytes("out.dat", abc, False)
なんでセーブできないのでしょうか?
構造体ごとファイル保存できる方がいらしたら教えてください。
# Interface では無いのに(Structure なのに)、先頭が大文字 I なのは違和感が…。
> なんでセーブできないのでしょうか?
引数定義をみるとわかるように、WriteAllBytes は Byte 配列を受け取るからです。
IData は Byte 配列に変換できないため、エラーになるというわけです。
どうしても WriteAllBytes で出力したいなら、変換演算子のオーバーロードが必要かと。
Public Structure IDATA
Public Data1 As Integer
Public Data2 As Integer
Public Data3 As Integer
Shared Widening Operator CType(ByVal e As IDATA) As Byte()
Using S As New System.IO.MemoryStream()
With New System.IO.BinaryWriter(S)
.Write(e.Data1)
.Write(e.Data2)
.Write(e.Data3)
End With
S.Position = 0
With New System.IO.BinaryReader(S)
Return .ReadBytes(S.Length)
End With
End Using
End Operator
End Structure
> 構造体ごとファイル保存できる方がいらしたら教えてください。
基本的には BinaryWriter を使って、メンバを一つ一つ出力する事になります。
メンバ単位ではなく、構造体丸ごと出力したい、という意図だとすれば、
手抜きな方法として、レガシ I/O 命令を使うという手法があります。
Dim f As Integer = FreeFile()
FileOpen(f, "out2.dat", OpenMode.Binary)
FilePut(f, abc)
FileClose(f)
また、出力形式に拘らないのであれば、シリアライザを使うのが楽でしょう。
<Serializable()> Public Structure IDATA
:
End Structure
のように、シリアル化可能の属性を付けておいた上で、
Dim path As String = "C:\out3.dat"
Dim fmt As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Using file As New System.IO.FileStream(path, System.IO.FileMode.CreateNew)
fmt.Serialize(file, abc)
End Using
のようにしてファイル化したり、あるいはそれを
Dim xyz As IDATA
Using file As New System.IO.FileStream(path, System.IO.FileMode.Open)
xyz = DirectCast(fmt.Deserialize(file), IDATA)
End Using
のようにして復元したりできます。
問題解決しました。
ありがとうございました。
ツイート | ![]() |