注册 登录
Office中国论坛/Access中国论坛 返回首页

ganlinlao的个人空间 http://www.office-cn.net/?230471 [收藏] [复制] [分享] [RSS]

日志

在FreeBasic中使用集合类(泛型)(第五节)--集合类的系列化和反系列化

已有 1746 次阅读2015-5-22 12:28 |个人分类:FreeBasic| Freebasic, Freebasic集合类

集合类的系列化和反系列化

(注:本节内容很重要,在后面的数据库对象映射,就依赖于集合类的系列化和反系列化,此内容要细细揣摩)

在使用集合时,您可能需要将集合中的内容序列化成字符串。所有的集合类都可以转换为普通的字符串。你可以使用 Cast(操作符),Str(函数) 或 本库中的tostring () 方法,很容易可以把集合中的内容序列化成字符串,但要将这些字符串反序列化到list或map或许更难一些。

mdCollectionsHelper 提供了一些静态方法:   (mdCollectionHelper自动引用了mdList.bi和mdMap.bi)

createList(String) As mdList(String)   :将字符串生成一个字符型list列表
createMap(String) As mdMap(String, String)  :将字符串生成一个map字典
encode(String) As String               :将一个普通字符串按区隔符"[]{}=,\r\n"等生成字符串
decode(String) As String                :去掉区隔符生成一个普通字符串

下面的例子将演示如何进行集合类的系列化:

#include once "md/helper/mdCollectionsHelper.bi"
'先声明好map的类型,mdCollectionsHelper很快会用到它
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

'声明之后的代码实现
constructor myclass()        
end constructor

'接下来的构造器用来初始化创建一个map对象,并将map的内容填入自定义类型的字段
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不是必须的,但对字符串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

'接下来开始实例化,并应用到具体的数据中
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
'让我们看看我们创建的列表的输出 — 事实上,我们可以通过网络将数据发送出去,或将它保存到一个文件或任何需要的地方......
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

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册

QQ|站长邮箱|小黑屋|手机版|Office中国/Access中国 ( 粤ICP备10043721号-1 )  

GMT+8, 2024-3-29 12:48 , Processed in 0.054370 second(s), 17 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

返回顶部