我有这个自定义类:
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/en-我们/图书馆/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);
}
这篇关于如何二进制序列化器自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!