使用Serializable
属性和实现ISerializable
接口有什么区别?
What's the difference between using the Serializable
attribute and implementing the ISerializable
interface?
当你使用 SerializableAttribute
属性 您在编译时将属性放在字段上,这样在运行时,序列化工具通过对类/模块/程序集类型执行反射,将知道根据属性序列化什么.
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.
[Serializable]
public class MyFoo { … }
上面表明序列化工具应该序列化整个类MyFoo
,而:
The above indicates that the serializing facility should serialize the entire class MyFoo
, whereas:
public class MyFoo
{
private int bar;
[Serializable]
public int WhatBar
{
get { return this.bar; }
}
}
使用该属性可以选择性地选择需要序列化的字段.
Using the attribute you can selectively choose which fields needs to be serialized.
当您实现 ISerializable
接口,通过覆盖 GetObjectData
和(并且通过提供 SetObjectData
MyFoo(SerializationInfo info, StreamingContext context)
形式的构造函数),可以更好地控制数据的序列化.
When you implement the ISerializable
interface, the serialization effectively gets overridden with a custom version, by overriding GetObjectData
and (and by providing a constructor of the form SetObjectData
MyFoo(SerializationInfo info, StreamingContext context)
), there would be a finer degree of control over the serializing of the data.
另请参阅 此 StackOverflow 上的自定义序列化示例一个>.它展示了如何使序列化与序列化数据的不同版本保持向后兼容.
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.
希望这会有所帮助.
这篇关于使用 Serializable 属性 & 有什么区别?实现 ISerializable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!