How to Binary Serializer Custom Class

别来无恙 提交于 2019-12-02 03:25:33

问题


I've this custom class:

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

obviously I also have constructor and get/set methods.

In my main form I initialize a lot of MyClass object (note that in MyClass object I have reference to other 2 MyClass objects). After initialization I iterate through a first MyClass item, call it for instance "root". So, for example I do something like:

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

and so on.

No I want to store in a binary file, all the MyClass object instantiated, in order to get them again after software restart.

I have totally no idea on how to do this, can someone please help me? Thanks.


回答1:


First add the attribute [Serializable] before the class declaration. More about the attributes go to: 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;
}

Note: all the class members must be also serializable. For serializing the object to binary you can use the following code sample:

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

And for the deserializing from binary:

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

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


来源:https://stackoverflow.com/questions/30918176/how-to-binary-serializer-custom-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!