列表C里是对应的VB.NET代码,后面是先前提到的类。
列表C
Public Class Config
Public Property WindowTitle() As String
Get
Return _wndowTitle
End Get
Set(ByVal Value As String)
_wndowTitle = Value
End Set
End Property
Public Property CopyrightText() As String
Get
Return _copyrightText
End Get
Set(ByVal Value As String)
_copyrightText = Value
End Set
End Property
Public Property CustomText() As String
Get
Return _customText
End Get
Set(ByVal Value As String)
_customText = Value
End Set
End Property
** _wndowTitle As String
** _copyrightText As String
** _customText As String
End Class
列表D是应用程序代码。
列表D
Imports System.IO
Imports System.Xml
Imports System.Xml.Serialization
Public Class Form1
Inherits System.Windows.Forms.FormReadOnlyfilepath As String
= "c:test.xml"
** Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
Dim cf As New Config
Dim ser As New XmlSerializer(cf.GetType)
Dim fs As FileStream
If (File.Exists(filepath))
Thenfs = New FileStream(filepath, FileMode.Open)cf = CType(ser.Deserialize(fs), Config)lblTitle.Text = cf.WindowTitlelblCopyright.Text = cf.CopyrightTexttxtInput.Text = cf.CustomTextfs.Close()
Elsefs = New FileStream(filepath, FileMode.CreateNew)lblTitle.Text = "TechRepublic.com Test
Application"lblCopyright.Text = "2005"
Dim tw As TextWritertw = New StreamWriter(fs)ser.Serialize(tw, cf)tw.Close()fs.Close()
End If
End Sub
** Sub btnSave_Click(ByVal
sender As System.Object, ByVal
e As System.EventArgs)
Handles btnSave.Click
Dim cf As New Config
With cf
.CopyrightText = lblCopyright.Text
.WindowTitle = lblTitle.Text
.CustomText = txtInput.Text
End With
Dim ser As New XmlSerializer(cf.GetType)
Dim tw As TextWritertw = New StreamWriter(filepath, False)ser.Serialize(tw, cf)tw.Close()
End Sub
End Class
在调入窗体的时候,有一个XML文件会被用来填充窗体里的控件。如果这个文件不存在,那么它就会被创建并被填充。这个窗体里有一个按钮,在被点击的时候会把数据保存在XML文件里。由于它是一个配置文件,所以当窗体被关闭或者数据值发生改变的时候,你可能需要自动地保存这个文件。
用C#和VB.NET分别编写成的代码有一些小小的不同之处,但是它们基本上是一样的。这两种语言之间的一个重要不同之处是大小写敏感性。VB.NET对大小写不敏感,所以需要对类成员变量加上下划线,以便将其与属性名区分开来,而在C#里却没有这个问题。这个简单应用的一个重要方面就是序列化。