What#39;s the difference between using the Serializable attribute amp; implementing ISerializable?(使用 Serializable 属性 amp; 有什么区别?实现 ISerializable?)
问题描述
使用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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Serializable 属性 & 有什么区别?实现 ISerializable?


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01