请教一个问题
我在VB中定一个A类
然后再定义一个A类的对象b
现在如何把b 以二进制方式写入到一个文件中请大家帮帮忙,急啊

解决方案 »

  1.   

    可以用PropertyBag来实现简单的串行化,当然VB提供的持久化方法也是用这个。如:
    '以下在Class1中
    Option ExplicitPublic id       As Long
    Public data     As VariantPublic Property Get Contents() As Variant
        
        Dim objPropBag  As PropertyBag
        
        Set objPropBag = New PropertyBag
        
        objPropBag.WriteProperty "id", id, 0
        objPropBag.WriteProperty "data", data, Empty
        
        Contents = objPropBag.Contents
        
        Set objPropBag = Nothing
        
    End PropertyPublic Property Let Contents(ByVal vData As Variant)
        
        Dim objPropBag  As PropertyBag
        
        Set objPropBag = New PropertyBag
        
        objPropBag.Contents = vData
        
        id = objPropBag.ReadProperty("id", 0)
        data = objPropBag.ReadProperty("data", Empty)
        
        Set objPropBag = Nothing
        
    End Property'测试' 把对象持久化并写入文件
    Private Sub Command1_Click()
        
        Dim obj         As Class1
        
        Dim vData()     As Byte
        Dim intFileNum  As Integer
        
        Set obj = New Class1
        
        obj.id = 123
        obj.data = "hello world"
        
        vData() = obj.Contents
        
        intFileNum = FreeFile()
        
        Open "c:\test.dat" For Binary As intFileNum
            Put intFileNum, , vData()
        Close intFileNum
        
    End Sub' 从文件中读取数据并还原对象
    Private Sub Command2_Click()
        
        Dim obj         As Class1
        
        Dim vData()     As Byte
        Dim intFileNum  As Integer
        
        Open "c:\test.dat" For Binary As intFileNum
            ReDim vData(LOF(intFileNum) - 1)
            Get intFileNum, , vData()
        Close intFileNum
        
        Set obj = New Class1
            
        obj.Contents = vData
        
        Debug.Print "id = "; obj.id
        Debug.Print "data = "; obj.data
        
    End Sub
      

  2.   

    sorry,上面最后一个方法有错误
    ' 从文件中读取数据并还原对象
    Private Sub Command2_Click()
        
        Dim obj         As Class1
        
        Dim vData()     As Byte
        Dim intFileNum  As Integer
        
        intFileNum = FreeFile()
        
        Open "c:\test.dat" For Binary As intFileNum
            ReDim vData(LOF(intFileNum) - 1)
            Get intFileNum, , vData()
        Close intFileNum
        
        Set obj = New Class1
            
        obj.Contents = vData
        
        Debug.Print "id = "; obj.id
        Debug.Print "data = "; obj.data
        
    End Sub