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


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01