.NET面试基础知识之序列化(Serialize)(一)

Serialization

A process of converting an object or a graph of connected objects into a stream bytes.

Deserialization

A process of converting a stream object of bytes back int its graph of connected objects.

ASP.NET saves and restores session state by way of serialization and dereliazation

When serialize an object graph, the formatter checks that every object's type is serializable. If an object in the graph is not serializable, the formatter's Serialize method throws the SerializationException 

The SerializableAttribute custom attribute may be applied to reference types, value types, enumerated types(enum) and delegate types only.(Enumerated and delegate types are always serializable so there is no need to explicitly apply for the SerializableAttribute)

The SerializableAttribute is not inherited by derived types. 如果要序列化子类,则子类与父类都必须有Serializable属性,否则抛出异常。

When you apply the SerializableAttribute to a type, all instance fields(public, private, protected, and so on) are serialized.

There are two reasons why you would not want some of a type's instance fields to be serialized.

  • The field contains information that would not be valid when deserialized. 
  • The field contains information that is easy calculated.

Use System.NoSerializedAttribute to indicate which fields of the type should not be serialized.

Code:

  [Serializable]
    internal class Circle
    {

    public int Radius
        [NonSerialized]
        public int Area;

        public Child(int radius)
        {

      this.Radius=radius;

      this.Area=Math.PI*Radius*Radius;
        }
    }

当序列化时area将不会被序列化,但是当反序列化时area会被默认复制为0,而不是实际值,可以用以下代码改正

[Serializable]
    internal class Circle
    {
        public int Radius {

            get;
            set;
        }
        [NonSerialized]
        public int Area {
            get;
            set;
        }
        public Circle(int radius)
        {
            this.Radius = radius;
            this.Area = Math.PI * Radius * Radius;
        }

        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {

            this.Area = Math.PI * Radius * Radius;
        }
    }

【OnDeserialized】[OnSerialized] before deserialization and serialization

[OnDeserializing][OnSerializing] after deserialization and serialization

When you are serializing a set of objects, the formatter first calls all of the object's methods that are marked with the OnSerializing attribute. Next it serializes all of the objects' fields, and finally it calls all of the objects' methods marked with OnSerialized attribute.

Similarly with deserialization.

When the formatters see OptionalFieldAttribute applied to a field, the formatter will not throw the SerializationException if the data in the stream does not contain the field.

原文地址:https://www.cnblogs.com/sift/p/3595991.html