why we can't Serialize these objects?

2019-08-27 03:02发布

问题:

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

""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 ??????

回答1:

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.

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.

EDIT:

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.

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.

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.



回答2:

The default binary serialization in .NET serializes a whole object graph, which, by its nature of being a graph, doesn't have a constant size, which means each serialization object (record) won't have a constant size, preventing random access.

To be able to randomly access any record in a file, write your own implementation of the binary serialization of your class, or use a database. If you need a simple, no-install single-threaded database engine, have a look at SQL Server Compact.