| Dim FS As New System.IO.FileStream("c:\test.txt", IO.FileMode.Create)
接着调用BinFormatter的Serialize方法序列化任何可以序列化的framework对象:
R = New Rectangle(rnd.Next(0, 100),rnd.Next(0, 300), _
rnd.Next(10, 40),rnd.Next(1, 9))
BinFormatter.Serialize(FS, R)
加一个Serializable属性使得自定义的对象可以序列化
<Serializable()> Public Structure Person
Dim Name As String
Dim Age As Integer
Dim Income As Decimal
End Structure
下面代码创建一个Person对象实例,然后调用BinFormatter的Serialize方法序列化自定义对象:
P = New Person()
P.Name = "Joe Doe"
P.Age = 35
P.Income = 28500
BinFormatter.Serialize(FS, P)
你也可以在同一个Stream中接着序列化其他对象,然后以同样的顺序读回。例如,在序列化Person对象之后接着序列化一个Rectangle对象:
BinFormatter.Serialize(FS, New Rectangle(0, 0, 100, 200))
创建一个BinaryFormatter对象,调用其Deserialize方法,然后把返回的值转化为正确的类型,就是整个反序列化过程。然后接着发序列化Stream的其他对象。
假定已经序列化了Person和Rectangle两个对象,以同样的顺序,我们反序列化就可以得到原来的对象:
Dim P As New Person()
P = BinFormatter.Serialize(FS, Person)
Dim R As New Rectangle
R = BinFormatter.Serialize(FS, Rectangle)
Persisting Collections
集合的存储
大多数程序处理对象集合而不是单个的对象。对于集合数据,首先创建一个数组(或者是其他类型的集合,比如ArrayList或HashTable),用对象填充,然后一个Serialize方法就可以序列化真个集合,是不是很简单?下面的例子,首先创建一个有两个Person对象的ArrayList,然后序列化本身:
Dim FS As New System.IO.FileStream _
上一页 [1] [2] [3] [4] 下一页 |