|
Public Class Class1
Private _Value1 As String = ""
Public Property Value1 As String
Get
Return Me._Value1
End Get
Set(value As String)
Me._Value1 = value
Call SaveClass1(Me) '値が変更された時ファイルに保存を行う
End Set
End Property
Private _Value2 As String = ""
Public Property Value2 As String
Get
Return Me._Value2
End Get
Set(value As String)
Me._Value2 = value
Call SaveClass1(Me) '値が変更された時ファイルに保存を行う
End Set
End Property
End Class
Module Module1
Const fileName As String = "D:\class1.xml"
'Class1をxmlファイルで保存
Public Sub SaveClass1(ByRef cls As Class1)
Try
Dim serializer As New System.Xml.Serialization.XmlSerializer(GetType(Class1))
Using sw As New System.IO.StreamWriter(fileName, False, New System.Text.UTF8Encoding(False))
serializer.Serialize(sw, cls)
End Using
Catch ex As System.IO.IOException
'xmlファイルを読込時発生するので無条件でスルー
End Try
End Sub
'xmlファイルを読み込みClass1に展開
Public Sub LoadClass1(ByRef cls As Class1)
If System.IO.File.Exists(fileName) Then
Dim serializer As New System.Xml.Serialization.XmlSerializer(GetType(Class1))
Using sr As New System.IO.StreamReader(fileName, New System.Text.UTF8Encoding(False))
cls = DirectCast(serializer.Deserialize(sr), Class1)
End Using
Else
cls = New Class1
End If
End Sub
End Module
テスト用フォーム
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button2.Click
'ストップウォッチを開始する
Dim sw As New System.Diagnostics.Stopwatch()
sw.Start()
Dim cls As Class1 = Nothing
Call LoadClass1(cls)
cls.Value1 = "test3"
cls.Value2 = "test4"
'ストップウォッチを止め結果を表示する
sw.Stop()
Debug.Print("{0}", sw.Elapsed)
End Sub
End Class
|