使用可序列化属性和使用可序列化属性有什么区别?实现ISerialized?
使用 Serialized
属性和实现 ISerialized
接口有什么区别?
What's the difference between using the Serializable
attribute and implementing the ISerializable
interface?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当您使用
SerializedAttribute
属性,您在编译时将属性放在字段上,这样在运行时,序列化工具将通过对类/模块执行反射来知道根据属性序列化什么内容/装配类型。
上面表明序列化工具应该序列化整个类
MyFoo
,而:使用该属性,您可以有选择地选择需要序列化的字段。
当您实现
ISerialized
接口,通过覆盖GetObjectData
和(以及通过提供SetObjectData
MyFoo(SerializationInfo info, StreamingContext context)
) 形式的构造函数,可以更好地控制数据的序列化。另请参阅StackOverflow 上的自定义序列化示例。它展示了如何保持序列化与序列化数据的不同版本向后兼容。
希望这有帮助。
When you use the
SerializableAttribute
attribute you are putting an attribute on a field at compile-time in such a way that when at run-time, the serializing facilities will know what to serialize based on the attributes by performing reflection on the class/module/assembly type.The above indicates that the serializing facility should serialize the entire class
MyFoo
, whereas:Using the attribute you can selectively choose which fields needs to be serialized.
When you implement the
ISerializable
interface, the serialization effectively gets overridden with a custom version, by overridingGetObjectData
and(and by providing a constructor of the formSetObjectData
MyFoo(SerializationInfo info, StreamingContext context)
), there would be a finer degree of control over the serializing of the data.See also this example of a custom serialization here on StackOverflow. It shows how to keep the serialization backwards-compatible with different versionings of the serialized data.
Hope this helps.
SerializedAttribute 指示框架执行默认的序列化过程。如果您需要更多控制,可以实现 ISerialized界面。然后,您可以在
GetObjectData
方法中放置您自己的代码来序列化该对象,并更新传递给它的SerializationInfo
对象。The SerializableAttribute instructs the framework to do the default serialization process. If you need more control, you can implement the ISerializable interface. Then you would put the your own code to serialize the object in the
GetObjectData
method and update theSerializationInfo
object that is passed in to it.ISerialized
接口允许您实现默认序列化之外的自定义序列化。当您实现
ISerialized
接口时,您必须重写GetObjectData
方法,如下所示The
ISerializable
interface lets you implement custom serialization other than default.When you implement the
ISerializable
interface, you have to overrideGetObjectData
method as followsISerialize 强制您手动实现序列化逻辑,而通过 Serialized 属性标记(您是认真的吗?)将告诉 Binary 序列化程序该类可以序列化。它会自动完成。
ISerialize forces you to implement serialization logic manually, while marking by Serializable attribute (did you mean it?) will tell Binary serializer that this class can be serialized. It will do it automatically.
从 ISerialized 继承允许您自定义实现(反)序列化。仅使用 Serialized 属性时,序列化(反)序列化只能由属性控制,灵活性较差。
Inheriting from ISerializable allows you to custom implement the (de)serialization. When using only the Serializable attribute, the (de)serialization can be controlled only by attributes and is less flexible.