为什么类 not marked with Serializable 不能用BinaryFormatter序列化?
Why classes not marked with Serializable cannot be serialized using BinaryFormatter?
我们都知道并在 MSDN 站点中提到:
The serialization architecture provided with the .NET Framework
correctly handles object graphs and circular references automatically.
The only requirement placed on object graphs is that all objects
referenced by the object that is being serialized must also be marked
as Serializable. If this is not done, an
exception will be thrown when the serializer attempts to serialize the
unmarked object.
我的问题是为什么应用此约束? (如果这是一个约束!;-))
BinaryFormatter 具有非常 不寻常的能力,没有其他类似于它的功能。它可以在没有 运行 构造函数的情况下创建 class 的对象。它可以为您的属性赋值 而无需 运行 属性 setter 访问器方法。
除此之外没有什么特别神奇的,它只是保留了 class 对象的字段值。并在对象反序列化时恢复它们。
并非每个 class 都适合这样处理,要么是出于安全考虑,要么是因为字段值太依赖于运行时状态。请注意安全性如何成为一个问题,因为攻击者可以操纵序列化数据并使您的对象进入不一致状态,即可利用的状态。说一个 IsAdministrator 属性。关键运行时状态的一个很好的例子是 Control.Handle 属性,当你反序列化时它永远不会有相同的值。
这些是 BinaryFormatter class 无法自行解决的实际限制。它需要帮助,明确表示这样做是安全的。当您将代码写入 de/serialize 对象时,这不可能是正式的 okay,这很容易,但实际上您对 class 的了解还不够,因为您没有编写它。 class 作者需要这样做,他通过给它赋予 [Serializable] 属性来做到这一点。
我相信 的答案回答了您关于为什么要应用此限制的问题 -
"to prevent data accidentally leaking across a remoting boundary"
即它在那里的原因是因为它是 BinaryFormatter 的设计决定,safe-guard 以确保程序员真正意味着要序列化的数据是由 BinaryFormatter 序列化的。
该 MSDN 文章还指出 -
a class cannot be made serializable after it has been compiled.
(意味着尝试通过使用反射添加属性类型使其在 execution-time 处可序列化)因此 BinaryFormatter 的实现的一个约束是必须指定 SerializableAttribute 以编译要使用序列化的类型它。
我们都知道并在 MSDN 站点中提到:
The serialization architecture provided with the .NET Framework correctly handles object graphs and circular references automatically. The only requirement placed on object graphs is that all objects referenced by the object that is being serialized must also be marked as Serializable. If this is not done, an exception will be thrown when the serializer attempts to serialize the unmarked object.
我的问题是为什么应用此约束? (如果这是一个约束!;-))
BinaryFormatter 具有非常 不寻常的能力,没有其他类似于它的功能。它可以在没有 运行 构造函数的情况下创建 class 的对象。它可以为您的属性赋值 而无需 运行 属性 setter 访问器方法。
除此之外没有什么特别神奇的,它只是保留了 class 对象的字段值。并在对象反序列化时恢复它们。
并非每个 class 都适合这样处理,要么是出于安全考虑,要么是因为字段值太依赖于运行时状态。请注意安全性如何成为一个问题,因为攻击者可以操纵序列化数据并使您的对象进入不一致状态,即可利用的状态。说一个 IsAdministrator 属性。关键运行时状态的一个很好的例子是 Control.Handle 属性,当你反序列化时它永远不会有相同的值。
这些是 BinaryFormatter class 无法自行解决的实际限制。它需要帮助,明确表示这样做是安全的。当您将代码写入 de/serialize 对象时,这不可能是正式的 okay,这很容易,但实际上您对 class 的了解还不够,因为您没有编写它。 class 作者需要这样做,他通过给它赋予 [Serializable] 属性来做到这一点。
我相信 的答案回答了您关于为什么要应用此限制的问题 -
"to prevent data accidentally leaking across a remoting boundary"
即它在那里的原因是因为它是 BinaryFormatter 的设计决定,safe-guard 以确保程序员真正意味着要序列化的数据是由 BinaryFormatter 序列化的。
该 MSDN 文章还指出 -
a class cannot be made serializable after it has been compiled.
(意味着尝试通过使用反射添加属性类型使其在 execution-time 处可序列化)因此 BinaryFormatter 的实现的一个约束是必须指定 SerializableAttribute 以编译要使用序列化的类型它。