温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

VB.NET如何实现集合存储

发布时间:2021-12-02 10:15:35 来源:亿速云 阅读:297 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关VB.NET如何实现集合存储,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

大多数程序处理对象集合而不是单个的对象。对于集合数据,首先创建一个数组(或者是其他类型的集合,比如ArrayList或HashTable),用对象填充,然后一个Serialize方法就可以序列化这个集合,是不是很简单?下面的例子,首先创建一个有两个Person对象的ArrayList,然后序列化本身:

  1. Dim FS As New System.IO.FileStream _  

  2. ("c:\test.txt", IO.FileMode.Create)  

  3. Dim BinFormatter As New Binary
    .BinaryFormatter()  

  4. Dim P As New Person()  

  5. Dim Persons As New ArrayList  

  6. P = New Person()  

  7. P.Name = "Person 1" 

  8. P.Age = 35 

  9. P.Income = 32000 

  10. Persons.Add(P)  

  11. P = New Person()  

  12. P.Name = "Person 2" 

  13. P.Age = 50 

  14. P.Income = 72000 

  15. Persons.Add(P)  

  16. BinFormatter.Serialize(FS, Persons) 

以VB.NET集合存储序列化数据的文件为参数,调用一个BinaryFormatter实例的Deserialize方法,就会返回一个对象,然后把它转化为合适的类型。下面的代码反序列化文件中的所有对象,然后处理所有的Person对象:

  1. FS = New System.IO.FileStream _  

  2. ("c:\test.txt", IO.FileMode.
    OpenOrCreate)  

  3. Dim obj As Object  

  4. Dim P As Person(), R As
     Rectangle()  

  5. Do  

  6. obj = BinFormatter.
    Deserialize(FS)  

  7. If obj.GetType Is GetType
    (Person) Then  

  8. P = CType(obj, Person)  

  9. ' Process the P objext  

  10. End If  

  11. Loop While FS.Position 
    < FS.Length - 1  

  12. FS.Close() 

下面的例子调用Deserialize方法反序列化这个集合,然后把返回值转换为合适的类型(Person):

  1. FS = New System.IO.FileStream
    ("c:\test.txt", IO.FileMode.
    OpenOrCreate)  

  2. Dim obj As Object  

  3. Dim Persons As New ArrayList  

  4. obj = CType(BinFormatter.
    Deserialize(FS), ArrayList)  

  5. FS.Close() 

关于“VB.NET如何实现集合存储”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI