VB.net的序列化与反序列化

废话
最近需要做一个功能就是保存一个类
这个类里面放了巨量的变量,为了保存它我想了很多办法,主要两个
1.序列化与反序列化
2.用反射来遍历整个类保存到txt中
反射是我最想用的办法,因为没用过,但是看了很多都没有看明白。只好用了序列化

正文
主要流程就是利用Formatter对象的Serialize方法来将Filestream序列化

类的序列化

<Serializable>//这个东西一定要加,他决定能不能序列化
Public Class Class1
    Public a As Int16 = 1
    Dim b As Int16 = 2
    Dim c As Int16 = 3
End Class

        Dim matter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Dim fStream As New FileStream(“Save.dat”, FileMode.Create)
        CLDs.a = 4 //这里将公开变量改一下做个实验
        matter.Serialize(fStream, CLDs)
        fStream.Close()

将序列化后的类再反序列化赋给一个类

     Dim fStream As New FileStream(“Save.dat”, FileMode.Open)
        Dim sfFormatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
        Clds2 = sfFormatter.Deserialize(fStream)
        fStream.Close()
        MsgBox(Clds2.a, 1, "成功!")

在序列化时会有一个.dat文件在bin文件夹下产生,必须要对它进行读取才能反序列化,

上一篇:用VB实现“木马”式隐形运行程序


下一篇:LeetCode-105-Construct Binary Tree from Preorder and Inorder Traversal