什么是[Serializable]以及何时使用它?

本文翻译自:What is [Serializable] and when should I use it?

I found out that some classes use the [Serializable] attribute. 我发现有些类使用[Serializable]属性。

  • What is it? 它是什么?
  • When should I use it? 我应该什么时候使用它?
  • What kinds of benefits will I get? 我会得到什么样的好处?

#1楼

参考:https://stackoom.com/question/Of5M/什么是-Serializable-以及何时使用它


#2楼

Here is short example of how serialization works. 以下是序列化工作原理的简短示例。 I was also learning about the same and I found two links useful. 我也在学习同样的东西,我发现两个链接很有用。 What Serialization is and how it can be done in .NET . 序列化是什么以及如何在.NET中完成

A sample program explaining serialization 解释序列化的示例程序

If you don't understand the above program a much simple program with explanation is given here . 如果你不理解上面的程序, 这里给出一个简单的解释程序。


#3楼

Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. 序列化是将对象转换为字节流以便存储对象或将其传输到内存,数据库或文件的过程。

How Serialization Works 序列化的工作原理

This illustration shows the overall process of serialization. 此图显示了序列化的整个过程。

在此输入图像描述

The object is serialized to a stream, which carries not just the data, but information about the object's type, such as its version, culture, and assembly name. 该对象被序列化为流,该流不仅包含数据,还包含有关对象类型的信息,例如其版本,区域性和程序集名称。 From that stream, it can be stored in a database, a file, or memory. 从该流中,它可以存储在数据库,文件或内存中。

Details in msdn. msdn中的详细信息


#4楼

Serialization 序列化

Serialization is the process of converting an object or a set of objects graph into a stream, it is a byte array in the case of binary serialization 序列化是将对象或一组对象图转换为流的过程,在二进制序列化的情况下它是一个字节数组

Uses of Serialization 序列化的使用

  1. To save the state of an object into a file, database etc. and use it latter. 将对象的状态保存到文件,数据库等中并使用后者。
  2. To send an object from one process to another (App Domain) on the same machine and also send it over wire to a process running on another machine. 在同一台计算机上将对象从一个进程发送到另一个进程(App Domain),并通过网络将其发送到另一台计算机上运行的进程。
  3. To create a clone of the original object as a backup while working on the main object. 在处理主对象时创建原始对象的克隆作为备份。
  4. A set of objects can easily be copied to the system's clipboard and then pasted into the same or another application 可以轻松地将一组对象复制到系统的剪贴板,然后粘贴到相同或另一个应用程序中

Below are some useful custom attributes that are used during serialization of an object 下面是一些在对象序列化过程中使用的有用的自定义属性

[Serializable] -> It is used when we mark an object's serializable [NonSerialized] -> It is used when we do not want to serialize an object's field. [Serializable] - >当我们标记一个对象的可序列化时使用它[NonSerialized] - >当我们不想序列化一个对象的字段时使用它。 [OnSerializing] -> It is used when we want to perform some action while serializing an object [OnSerialized] -> It is used when we want to perform some action after serialized an object into stream. [OnSerializing] - >当我们想要在序列化对象时执行某些操作时使用它[OnSerialized] - >当我们想要在将对象序列化为流之后执行某些操作时使用它。

Below is the example of serialization 以下是序列化的示例

[Serializable]
    internal class DemoForSerializable
    {
        internal string Fname = string.Empty;
        internal string Lname = string.Empty;

        internal Stream SerializeToMS(DemoForSerializable demo)
        {
            DemoForSerializable objSer = new DemoForSerializable();
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, objSer);
            return ms;
        }

        [OnSerializing]
        private void OnSerializing(StreamingContext context) {
            Fname = "sheo";
            Lname = "Dayal";
        }
        [OnSerialized]
        private void OnSerialized(StreamingContext context)
        {
       // Do some work after serialized object
        }

    }

Here is the calling code 这是调用代码

class Program
    {
        string fname = string.Empty;
        string Lname = string.Empty; 

       static void Main(string[] args)
        {
            DemoForSerializable demo = new DemoForSerializable();

            Stream ms = demo.SerializeToMS(demo);
            ms.Position = 0;

            DemoForSerializable demo1 = new BinaryFormatter().Deserialize(ms) as DemoForSerializable;

            Console.WriteLine(demo1.Fname);
            Console.WriteLine(demo1.Lname);
            Console.ReadLine();
        }

    }

#5楼

Since the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter. 由于最初的问题是关于SerializableAttribute,因此应该注意,此属性仅在使用BinaryFormatter或SoapFormatter时适用。

It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is. 这有点令人困惑,除非你真正关注细节,何时使用它以及它的实际目的是什么。

It has NOTHING to do with XML or JSON serialization. 它与XML或JSON序列化无关。

Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. 与SerializableAttribute一起使用的是ISerializable Interface和SerializationInfo类。 These are also only used with the BinaryFormatter or SoapFormatter. 这些也只与BinaryFormatter或SoapFormatter一起使用。

Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. 除非您打算使用Binary或Soap序列化您的类,否则不要将您的类标记为[Serializable]。 XML and JSON serializers are not even aware of its existence. XML和JSON序列化程序甚至都不知道它的存在。


#6楼

What is it? 它是什么?

When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. 在.Net框架应用程序中创建对象时,无需考虑如何将数据存储在内存中。 Because the .Net Framework takes care of that for you. 因为.Net Framework会为您解决这个问题。 However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. 但是,如果要将对象的内容存储到文件,将对象发送到另一个进程或通过网络传输,则必须考虑如何表示对象,因为您需要转换为其他格式。 This conversion is called SERIALIZATION. 此转换称为SERIALIZATION。

Uses for Serialization 用于序列化

Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. 序列化允许开发人员保存对象的状态并根据需要重新创建它,提供对象的存储以及数据交换。 Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications. 通过序列化,开发人员可以执行诸如通过Web服务将对象发送到远程应用程序,将对象从一个域传递到另一个域,将对象作为XML字符串传递到防火墙,或者维护安全性或特定于用户的操作跨应用程序的信息

Apply SerializableAttribute to a type to indicate that instances of this type can be serialized. SerializableAttribute应用于类型以指示可以序列化此类型的实例。 Apply the SerializableAttribute even if the class also implements the ISerializable interface to control the serialization process. 即使该类还实现了ISerializable接口来控制序列化过程,也应用SerializableAttribute

All the public and private fields in a type that are marked by the SerializableAttribute are serialized by default, unless the type implements the ISerializable interface to override the serialization process. 默认情况下, SerializableAttribute化由SerializableAttribute标记的类型中的所有公共和私有字段,除非该类型实现ISerializable接口以覆盖序列化过程。 The default serialization process excludes fields that are marked with NonSerializedAttribute . 默认序列化过程会排除使用NonSerializedAttribute标记的字段。 If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute to that field. 如果可序列化类型的字段包含特定于特定环境的指针,句柄或某些其他数据结构,并且无法在不同环境中进行有意义的重构,则可能需要将NonSerializedAttribute应用于该字段。

See MSDN for more details. 有关详细信息,请参阅MSDN

Edit 1 编辑1

Any reason to not mark something as serializable 任何不将某些东西标记为可序列化的理由

When transferring or saving data, you need to send or save only the required data. 传输或保存数据时,只需发送或保存所需数据。 So there will be less transfer delays and storage issues. 因此,传输延迟和存储问题将会减少。 So you can opt out unnecessary chunk of data when serializing. 因此,您可以在序列化时选择不必要的数据块。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值