Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

c# - How to Binary Serializer Custom Class

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...