使用 Serializable 属性 & 有什么区别?实现 ISerializable?

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)