A simple summary of C # serialization and deserialization

Source: Internet
Author: User

Related classes:

System.SerializableAttribute attributes (or properties),

System.Runtime.Serialization.Iserializable (custom serialization interface),

System.Runtime.Serialization.IserializationSurrogate (custom serialization proxy interface),

System.Runtime.Serializatin.SurrogateSelector (Custom serialization proxy settings Class)

1 : Official Notes

Serialization uses

BinaryFormatter (https://msdn.microsoft.com/zh-cn/library/ system.runtime.serialization.formatters.binary.binaryformatter.aspx) or

Sopaformatter (https://msdn.microsoft.com/zh-cn/library/ system.runtime.serialization.formatters.soap.soapformatter.aspx), using a similar method.

System.SerializableAttribute Features:

Applying the SerializableAttribute attribute to a type can indicate that an instance of that type can be ordered. If the person in the graph of the object being serialized and potent does not apply the SerializableAttribute attribute, the common language runtime throws Serializableexception (HTTPS://MSDN.MICROSOFT.COM/ZH-CN /library/system.runtime.serialization.serializationexception.aspx).

Even if the class implements ISerializable (Https://msdn.microsoft.com/zh-cn/library/system.runtime.serialization.iserializable.aspx ) interface to control the serialization process and still apply the SerializableAttribute attribute.

When the SerializableAttribute attribute is applied to a type, serialization is by default all private and public fields. You can serialize granularly processing by implementing an interface ISerializable rewrite serialization control.

You can also apply the NonSerializedAttribute (https://msdn.microsoft.com/zh-cn/library/system.nonserializedattribute.aspx) attribute to a field from the serialization exclusion field. If a field of a serializable type contains pointers, handles, or other models of data structures that are specific to a particular environment and can no longer be rebuilt in a different environment in an objectionable manner, it is best to apply the Nonserializableattribute attribute to the field.

system.runtime.serialization.iserializable interface:

Any class that can be serialized must be marked with SerializableAttribute. If a class requires a controller serialization process, it can implement the ISerializable interface. Formatter (https://msdn.microsoft.com/zh-cn/library/system.runtime.serialization.formatter.aspx) Called GetObjectData at serialization (https://msdn.microsoft.com/zh-cn/library/ system.runtime.serialization.iserializable.getobjectdata.aspx) and populates the provided SerializationInfo with all the data required to represent the object (https:// msdn.microsoft.com/zh-cn/library/system.runtime.serialization.serializationinfo.aspx). Formatter uses the type of objects in the drawing to create the SerializationInfo. Objects that need to send their own proxies can use Fulltypename on SerializationInfo (https://msdn.microsoft.com/zh-cn/library/ system.runtime.serialization.serializationinfo.fulltypename.aspx) and AssemblyName (https://msdn.microsoft.com/ Zh-cn/library/system.runtime.serialization.serializationinfo.assemblyname.aspx) method to change the information that is being transmitted.

In the case of class inheritance, you can serialize a class derived from a base class that implements ISerializable. In this case, the derived class should call the base class implementation of getobjectdata within the implementation of the GetObjectData. Otherwise, data from the base class is not serialized.

The ISerializable interface represents a constructor with a signature (Serializationinfo,streamingcontext). When deserializing, the current constructor is called only after the formatter has deserialized the data in SerializationInfo. Generally, this constructor should be protected if the class is not sealed.

It is not possible to guarantee the order in which objects are deserialized. For example, if a type references a type that has not been deserialized, an exception is thrown. If you create a type with this dependency, you can pass the Ideserializationcallback (https://msdn.microsoft.com/zh-cn/library/ System.runtime.serialization.ideserializationcallback.aspx) interface and the OnDeserialization method to resolve the problem.

The serialized interface handles the same type as the extended object, processing the extended MarshalByRefObject (https://msdn.microsoft.com/zh-cn/library/ System.marshalbyrefobject.aspx) object type. These types can be tagged with SerializableAttribute, and the ISerializable interface can be implemented as any other object type. Their object state will be captured and persisted in the stream.

When these types are used through System.Runtime.Remotting, the remoting interface provides a surrogate that supersedes the usual serialization and serializes the proxy to MarshalByRefObject. A surrogate is a helper that knows how to serialize and deserialize a particular type of object. The agent is not visible to the user in most cases, and the type will be ObjRef (https://msdn.microsoft.com/zh-cn/library/system.runtime.remoting.objref.aspx).

As a general design pattern, classes rarely use serializable attributes to mark and extend MarshalByRefObject. When combining these two features, developers should carefully consider possible serialization and remoting scenarios. MemoryStream (https://msdn.microsoft.com/zh-cn/library/system.io.memorystream.aspx) is a suitable example. When the base class of MemoryStream is extended from MarshalByRefObject, you can capture the state of MemoryStream and restore it at any time. Therefore, it might make sense to serialize the state of the stream into the database and restore it at a later time. However, when used through remoting, this type of object sets the proxy.

For more information about the derived classes for serializing MarshalByRefObject, see Remottingsurrogateselector (https://msdn.microsoft.com/zh-cn/library/ system.runtime.remoting.messaging.remotingsurrogateselector.aspx). For more information about implementing ISerializable, see Custom Serialization (Https://msdn.microsoft.com/zh-cn/library/ty01x675.aspx).

System.Runtime.Serialization.IserializationSurrogate Interface:

Implements the serialization proxy selector, which allows one object to serialize and deserialize another object.

System.Runtime.Serializatin.SurrogateSelector class:

The serialization surrogate provides the user with an object that can handle the serialization requirements of different objects, and can convert serialized data if necessary. This class implements the interface System.Runtime.Serializatin.IsurrogateSelector.

System.Runtime.Serializatin.IsurrogateSelector Interface:

The surrogate selector implements the Isurrogateselector interface to help the formatter select a surrogate to delegate to other objects for serialization or deserialization.

2 : Simple Serialization

The classes that need to be used have SerializableAttribute attributes, and BinaryFormatter, which are decorated with Nonserializableattribute attributes for class members that do not need or should not be serialized.

The code is as follows:

[Serializable]

public class myitemtype{

Other Members ...

[Nonserializable]

public string ignorfield{...}

}

Serialization process

string filename = "[FileName]";

Myitemtype t = new Myitemtype ();

FileStream fs = new FileStream (filename,filemode.create);

Ifromatter formatter = new BinaryFormatter ();

Formatter. Serialize (FS, t);

Fs. Close ();

Deserialization process

string filename = "[FileName]";

Myitemtype result = null;

FileStream fs = new FileStream (FileName, FileMode.Open);

IFormatter formatter = new BinaryFormatter ();

result = Formatter. Deserialize (FS);

Fs. Close ();

3 : Using Iserializable interface for custom serialization

Inheriting the ISerializable interface requires implementing method GetObjectData and adding a construction method with the signature SerializationInfo info and StreamingContext context for deserialization use. It is important to note that the access modifier for this construction method is ignored during deserialization, so it should be used with stricter access modifiers such as protected or private to prevent this construction method from being called incorrectly.

Classes that implement this interface should also use the SerializableAttribute adornment.

code example:

[Serializable]

public class Myitemtype:isereializable

{

Field....

#region Custom Serialization

Private Myitemtype (SerializationInfo info, StreamingContext context)

{

Thisobjectstringfield = info. GetValue ("KeyName", typeof (String));

Thisobjectintfield = info. GetInt32 ("keyName2");

}

public override void GetObjectData (SerializationInfo info, StreamingContext context)

{

Info. AddValue ("KeyName", Thisobjectstringfield, typeof (String));

Info. AddInt32 ("KeyName", Thisobjectintfield);//This line error, info does not have a strongly typed value Add method

}

#endregion

}

How to use the same method as in a simple serialized code instance

4 : Using iserializationsurrogate the serialization surrogate for an interface implementation

Use the Iserializationsurrogate implementation class to serialize and deserialize another class.

The class or interface used by this serialization also includes the SurrogateSelector class selected for the surrogate, IFormatter implementation class (use BinaryFormatter here)

Example code:

Customizing the serialization Agent

public class Surrogate:iserializationsurrogate

{

public void GetObjectData (Object obj, SerializationInfo info, StreamingContext context)

{

if (obj is Myitemtype)

{

Myitemtype temp = (myitemtype) obj;

Info. AddValue ("props", temp, typeof (String));

}

}

public object SetObjectData (Object obj, SerializationInfo info, StreamingContext context, isurrogateselector selector)

{

if (obj is Myitemtype)

{

Myitemtype temp = (myitemtype) obj;

Temp. MyProperty = (string) info. GetValue ("Props", typeof (String));

Console.WriteLine ("SetObjectData");

return temp;

}

return null;

}

How to use

Surrogate surrogate = new surrogate ();

SurrogateSelector selector = new SurrogateSelector ();

Selector. Addsurrogate (typeof (Myitemtype), New StreamingContext (Streamingcontextstates.all), surrogate);

Formatter. SurrogateSelector = selector;

FileStream fs = new FileStream (FileName, FileMode.Open);

Formatter. Deserialize (FS);

Fs. Close ();

Summary time: 2015/3/17

A simple summary of C # serialization and deserialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.