如何自定义二进制序列化程序 Class

How to Binary Serializer Custom Class

我有这个习惯class:

public class MyClass
{ 
    private byte byteValue;
    private int intValue;
    private MyClass myClass1= null;
    private MyClass myClass2 = null;
}

显然我还有构造函数和 get/set 方法。

在我的主窗体中,我初始化了很多 MyClass 对象(请注意,在 MyClass 对象中,我引用了其他 2 个 MyClass 对象)。初始化后,我遍历第一个 MyClass 项,例如调用它 "root"。所以,例如我做这样的事情:

MyClass myClassTest = root.getMyClass1();
MyClass myClassTest2 = myClassTest.getMyClass1();

等等。

不,我想将实例化的所有MyClass对象存储在二进制文件中,以便在软件重启后再次获取它们。

我完全不知道该怎么做,有人可以帮我吗? 谢谢。

首先在class声明之前添加属性[Serializable]。有关属性的更多信息,请访问:https://msdn.microsoft.com/en-us/library/z0w1kczw.aspx

[Serializable]
public class MyClass
{ 
    private byte byteValue;
    private int intValue;
    private MyClass myClass1= null;
    private MyClass myClass2 = null;
}

注意:所有 class 成员也必须是可序列化的。 要将对象序列化为二进制文件,您可以使用以下代码示例:

using (Stream stream = File.Open(serializationPath, FileMode.Create))
        {
            var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToSerialize);
            stream.Close();
        }

以及从二进制反序列化:

using (Stream stream = File.Open(serializationFile, FileMode.Open))
        {
            var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            deserializedObject = (MyClass)binaryFormatter.Deserialize(stream);
        }