如何二进制序列化程序自定义类 [英] How to Binary Serializer Custom Class
问题描述
我有这个自定义类:
public class MyClass
{
private byte byteValue;
private int intValue;
private MyClass myClass1= null;
private MyClass myClass2 = null;
}
很明显,我也有构造函数和get/set方法.
obviously I also have constructor and get/set methods.
在我的主要形式中,我初始化了许多MyClass
对象(请注意,在MyClass
对象中,我引用了其他2个MyClass对象).初始化后,我遍历第一个MyClass
项,将其称为"root".因此,例如,我做类似的事情:
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();
以此类推.
否,我想将所有MyClass
对象都实例化,以存储在二进制文件中,以便在软件重新启动后再次获取它们.
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.
推荐答案
首先在类声明之前添加属性[Serializable].有关属性的更多信息,请访问: https://msdn.microsoft.com/zh-我们/library/z0w1kczw.aspx
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);
}
这篇关于如何二进制序列化程序自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!