为什么我们不能序列化这些对象? [英] why we can't Serialize these objects?

查看:51
本文介绍了为什么我们不能序列化这些对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们不能将对象序列化为随机访问文件?另一方面,我们可以将对象序列化为顺序访问文件?

why we can't Serialize objects into Random Access file ? and on the other hand we can serialize objects into sequential access file ?

""C# 不提供在运行时获取对象大小的方法.这意味着,如果我们序列化类,我们不能保证固定长度的记录大小"(来自我读过的书).

""C# does not provide a means to obtain an object’s size at runtime. This means that, if we serialize the class, we cannot guarantee a fixed-length record size "" (from the book that i read in).

所以我们无法读取随机访问文件,因为我们不知道文件中的每个对象大小,所以我们如何进行查找??????

so we cannot read the the random access file because we don't know every object size in the file so how we could do seeking ??????

推荐答案

任何标有 SerializableAttribute 属性的对象都可以序列化(在大多数情况下).序列化的结果总是指向一个流,它很可能是一个文件输出流.

Any object marked with the SerializableAttribute attribute can be serialized (in most scenarios). The result from serialization is always directed to a stream, which may very well be a file output stream.

您是在问为什么不能部分反序列化对象图吗?.NET 序列化仅 [反] 序列化完整的对象图.否则,您将不得不求助于其他序列化格式化程序,或者自己编写.

Are you asking why an object graph cannot be deserialized partially? .NET serialization only [de]serializes complete object graphs. Otherwise you'll have to turn to other serialization formatters, or write your own.

要直接随机访问文件,您必须使用支持查找的流打开文件.

For direct random access to a file, you must open the file with a stream that supports seeking.

在序列化的结果流中寻找没有实际目的 - 只有序列化格式化程序知道那里有什么,并且应该始终在流的开始处提供.

Seeking in the resulting stream from a serialization has no practical purpose - only the serialiation formatter knows what's in there anyway and should always be fed the very start of the stream.

用于将数据持久化到其他结构中;在两阶段过程中进行:首先,将序列化字节定位到 [i.e.memory-backed] 流,您可以随后从中读取大小,然后使用所述大小知识将数据写入实际的后备存储.

For persisting the data into other structures; do it in a two-stage process: First, target the serialization bytes to a [i.e. memory-backed] stream that you can read the size from afterwards, then write the data to the actual backing store, using said knowledge of size.

您无法预测序列化对象的大小,因为序列化表示可能与运行时表示有很大不同.

You can't predict the size of a serialized object, because the serialized representation might differ a lot from the runtime representation.

如果您只使用原始类型并且使用 BinaryWriter 编写,仍然可以实现对输出大小的精确控制 - 但这本身并不是序列化.

It it still possible to achieve exact control over output size, if you use only primitive types, and you write using a BinaryWriter - but that is not serialization per-se.

这篇关于为什么我们不能序列化这些对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆