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?


基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30