VB.NET對(duì)象存儲(chǔ)各種方法簡(jiǎn)介
VB.NET編程語(yǔ)言為我們帶來(lái)了非常大的好處,尤其是在程序開發(fā)效率上,有了大大的提高。我們?cè)谶@里會(huì)為大家介紹VB.NET對(duì)象存儲(chǔ)的相關(guān)操作方法,希望能給大家?guī)?lái)一些幫助,提高大家的實(shí)際編程效率。
VB.NET對(duì)象存儲(chǔ)采用BinaryFormatte以二進(jìn)制的形式,或者用SoapFormatter類以XML格式都可以序列化一個(gè)具體的對(duì)象。只要把所有BinaryFormatter的引用改為SoapFormatter,無(wú)需改變?nèi)魏未a,就可以以XML格式序列化對(duì)象。
VB.NET對(duì)象存儲(chǔ)時(shí)首先創(chuàng)建一個(gè)BinaryFormatter實(shí)例:
- Dim BinFormatter As
New Binary.BinaryFormatter()
然后創(chuàng)建一個(gè)用于用于VB.NET對(duì)象存儲(chǔ)的序列化對(duì)象的FileStream對(duì)象:
- Dim FS As New System.IO.
FileStream("c:\test.txt",
IO.FileMode.Create)
接著調(diào)用BinFormatter的Serialize方法序列化任何可以序列化的framework對(duì)象:
- R = New Rectangle(rnd.
Next(0, 100),rnd.Next(0, 300), _- rnd.Next(10, 40),rnd.Next(1, 9))
- BinFormatter.Serialize(FS, R)
加一個(gè)Serializable屬性使得自定義的對(duì)象可以序列化
- < Serializable()>
- Public Structure Person
- Dim Name As String
- Dim Age As Integer
- Dim Income As Decimal
- End Structure
下面代碼創(chuàng)建一個(gè)Person對(duì)象實(shí)例,然后調(diào)用BinFormatter的Serialize方法序列化自定義對(duì)象:
- P = New Person()
- P.Name = "Joe Doe"
- P.Age = 35
- P.Income = 28500
- BinFormatter.Serialize(FS, P)
你也可以在同一個(gè)Stream中接著序列化其他對(duì)象,然后以同樣的順序讀回。例如,在序列化Person對(duì)象之后接著序列化一個(gè)Rectangle對(duì)象:
- BinFormatter.Serialize
(FS, New Rectangle
(0, 0, 100, 200))
創(chuàng)建一個(gè)BinaryFormatter對(duì)象,調(diào)用其Deserialize方法,然后把返回的值轉(zhuǎn)化為正確的類型,就是整個(gè)反序列化過(guò)程。然后接著發(fā)序列化Stream的其他對(duì)象。
假定已經(jīng)序列化了Person和Rectangle兩個(gè)對(duì)象,以同樣的順序,我們反序列化就可以得到原來(lái)的對(duì)象:
- Dim P As New Person()
- P = BinFormatter.Serialize
(FS, Person)- Dim R As New Rectangle
- R = BinFormatter.Serialize
(FS, Rectangle)
以上就是對(duì)VB.NET對(duì)象存儲(chǔ)的相關(guān)操作介紹。
【編輯推薦】