集合類的系列化和反系列化
(注:本節(jié)內(nèi)容很重要,在后面的數(shù)據(jù)庫對(duì)象映射,就依賴于集合類的系列化和反系列化,此內(nèi)容要細(xì)細(xì)揣摩)
在使用集合時(shí),您可能需要將集合中的內(nèi)容序列化成字符串。所有的集合類都可以轉(zhuǎn)換為普通的字符串。你可以使用 Cast(操作符),Str(函數(shù)) 或 本庫中的tostring () 方法,很容易可以把集合中的內(nèi)容序列化成字符串,但要將這些字符串反序列化到list或map或許更難一些。
mdCollectionsHelper 提供了一些靜態(tài)方法: (mdCollectionHelper自動(dòng)引用了mdList.bi和mdMap.bi)
createList(String) As mdList(String) :將字符串生成一個(gè)字符型list列表
createMap(String) As mdMap(String, String) :將字符串生成一個(gè)map字典
encode(String) As String :將一個(gè)普通字符串按區(qū)隔符"[]{}=,\r\n"等生成字符串
decode(String) As String :去掉區(qū)隔符生成一個(gè)普通字符串
下面的例子將演示如何進(jìn)行集合類的系列化:
#include once "md/helper/mdCollectionsHelper.bi"
'先聲明好map的類型,mdCollectionsHelper很快會(huì)用到它
mdMapDeclare(string,string)
'定義一些自定義類型(或類)
type Myclass
declare constructor()
declare constructor( byref m as mdMap(string,string)
declare operator cast() as string ‘必須聲明
label as string
value as integer
weight as double
end type
'聲明之后的代碼實(shí)現(xiàn)
constructor myclass()
end constructor
'接下來的構(gòu)造器用來初始化創(chuàng)建一個(gè)map對(duì)象,并將map的內(nèi)容填入自定義類型的字段
constructor myClass(byref m as mdmap(string,string))
this.label=mdcollectionsHelper.decode(m.get("label")
this.value=valint(m.get("value"))
this.weight=val(m.get("weight"))
end constructor
operator myclass.cast() as string
dim temp as string
dim m as mdMap(string,string)
temp=m.put("label",mdcollectionsHelper.encode(this.label)) ‘encode不是必須的,但對(duì)字符串encode也不是什么壞主意
temp=m.put("value",str(this.value))
temp=m.put("weight",str(this.weight))
return m
end operator
operator =(byref lhs as myclass,byref rhs as myclass) as boolean
return str(lhs)=str(rhs)
end operator
'接下來開始實(shí)例化,并應(yīng)用到具體的數(shù)據(jù)中
mdListDeclare(myclass)
dim listofMyclass as mdlist(myclass)
For i As Integer = LBound(firstArray) To UBound(firstArray)
firstArray(i).label = "label" & Str(i)
firstArray(i).value = i
firstArray(i).weight = i * 1.1
listOfMyClass.add(firstArray(i))
Next
'讓我們看看我們創(chuàng)建的列表的輸出 — 事實(shí)上,我們可以通過網(wǎng)絡(luò)將數(shù)據(jù)發(fā)送出去,或?qū)⑺4娴揭粋(gè)文件或任何需要的地方......
Dim As String stringRepresentation = listOfMyClass
Print "List as string: " & stringRepresentation
Print
'將字符串反序列回列表
Dim As mdList(String) listOfMaps = mdCollectionsHelper.createList(stringRepresentation)
Dim As MyClass newArray(0 To listOfMaps.size() - 1)
For i As Integer = LBound(newArray) To UBound(newArray)
newArray(i) = Type<MyClass>(mdCollectionsHelper.createMap(listOfMaps.get(i)))
Print i, newArray(i)
Next
Sleep