Serializing and Searching Object Collections

前端 未结 1 363
轮回少年
轮回少年 2020-12-22 09:10

I would appreciate if somebody could answer some questions regarding storing and searching object collections please. If you could give a basic example of any suggestions I

相关标签:
1条回答
  • 2020-12-22 09:41

    A simple List(Of Computer) is indeed all you need unless there is some other unknown requirement. Saving is very simple using serialization for this type of thing, and would work the same for a List or Collection<T>.

    Imports System.Collections.ObjectModel
    
    Public Class ComputersCollection
        Inherits Collection(Of Computer)
        ' NOT the crude thing in the VB NameSpace
    
        ' there is almost nothing to add: item, add and remove
        ' are in the base class
        ' ... perhaps saving and retrieving them by a key (name)
        ' which may do away with the search procedure in the posted code
    
    End Class
    
    Private Computers As New Collection(Of Computer)
    ' or
    Private Computers As New List(Of Computer)
    

    The other part, saving your collection, can be simple with serialization. First, you will have to add the Serializable attribute to your Computer class:

    <Serializable>
    Public Class Computer
    

    If you forget, you get the error Class foobar is not marked as serializable. Save to disk:

    Imports System.Runtime.Serialization
    
    Private myComputerFile As String = ...
    
    Dim bf As New BinaryFormatter
    Using fs As New FileStream(myComputerFile , FileMode.OpenOrCreate)
        bf.Serialize(fs, Computers)
    End Using
    

    Then you can recreate the List or Collection just as easily; this time the List:

    ' ToDo: add a check to skip if file is not there
    ' as in the first time run
    Dim bf As New BinaryFormatter
    Using fs As New FileStream(myComputerFile , FileMode.Open)
        Computers = CType(bf.Deserialize(fs), List(Of Computers))
    End Using
    

    Alternatively you can use the XML serializer to create an XML File or use the faster, smarter binary serializer is ProtoBuf-Net

    0 讨论(0)
提交回复
热议问题