使用Serializable
属性和实现ISerializable
接口(interface)有什么区别?
最佳答案
当您使用 SerializableAttribute
attribute 你在编译时将一个属性放在一个字段上,这样在运行时,序列化工具将通过对类/模块/程序集类型执行反射来知道根据属性序列化什么。
[Serializable]
public class MyFoo { … }
以上表明序列化工具应该序列化整个类 MyFoo
,而:
public class MyFoo
{
private int bar;
[Serializable]
public int WhatBar
{
get { return this.bar; }
}
}
使用该属性,您可以有选择地选择需要序列化的字段。
当您实现 ISerializable
interface , 通过覆盖 GetObjectData
,序列化有效地被自定义版本覆盖 和 (并通过提供 SetObjectData
MyFoo(SerializationInfo info, StreamingContext context)
形式的构造函数),会有更好的控制程度关于数据的序列化。
另见 this example of a custom serialization here on StackOverflow .它展示了如何使序列化向后兼容序列化数据的不同版本。
希望这对您有所帮助。
关于c# - 使用 Serializable 属性和实现 ISerializable 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2365152/