为什么要序列化的对象需要 Serializable 属性 [英] Why is Serializable Attribute required for an object to be serialized

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

问题描述

根据我的理解,SerializableAttribute 不提供编译时检查,因为它都是在运行时完成的.如果是这样,那么为什么需要将类标记为可序列化?

Based on my understanding, SerializableAttribute provides no compile time checks, as it's all done at runtime. If that's the case, then why is it required for classes to be marked as serializable?

序列化器不能只是尝试序列化一个对象然后失败吗?这不就是它现在所做的吗?当某些东西被标记时,它会尝试并失败.如果必须将事物标记为不可序列化而不是可序列化不是更好吗?这样你就不会遇到库没有将事物标记为可序列化的问题?

Couldn't the serializer just try to serialize an object and then fail? Isn't that what it does right now? When something is marked, it tries and fails. Wouldn't it be better if you had to mark things as unserializable rather than serializable? That way you wouldn't have the problem of libraries not marking things as serializable?

推荐答案

据我所知,SerializableAttribute 背后的想法是为二进制序列化.

As I understand it, the idea behind the SerializableAttribute is to create an opt-in system for binary serialization.

请记住,与使用公共属性的 XML 序列化不同,二进制序列化默认获取所有私有字段.

Keep in mind that, unlike XML serialization, which uses public properties, binary serialization grabs all the private fields by default.

这不仅可能包括不应公开的操作系统结构和私有数据,而且反序列化可能会导致可能导致应用程序崩溃的损坏状态(愚蠢的示例:文件在另一台计算机上打开).

Not only this could include operating system structures and private data that is not supposed to be exposed, but deserializing it could result in corrupt state that can crash an application (silly example: a handle for a file open in a different computer).

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

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