Serializable serialization examples in C #

Source: Internet
Author: User

The examples in this article describe serializable serialization in C #. Share to everyone for your reference. The specific analysis is as follows:

Overview:

Serialization is the process of converting an object into a format that is easy to transfer, typically converting a stream file into a memory or IO file. For example, you can serialize an object, and then use HTTP to transfer the object between the client and the server over the Internet, or share it with other applications. Conversely, deserialization reconstructs an object based on a stream.


One, several kinds of serialization technology

1) binary serialization preserves the type fidelity, which is useful for preserving the state of an object between different invocations of the application. For example, you can share objects between different applications by serializing them to the Clipboard. You can serialize objects to streams, disks, memory, networks, and so on. Remoting uses serialization to pass objects by value between a computer or an application domain.

2) XML serialization only serializes public properties and fields, and does not maintain type fidelity. This is useful when you want to provide or use data without restricting the applications that use that data. Because XML is an open standard, this is a good choice for sharing data over the WEB. SOAP is also an open standard, which makes it an attractive option as well.

3) Use the provided data contract to serialize and deserialize the type instance into an XML stream or document (or JSON format). Often applied to WCF communication.


Second, the classification of serialization


1. Basic serialization

The simplest way to make a class serializable is to use the Serializable property to tag it, as shown below


The code is as follows:

[Serializable]

public class MyObject

{

public int n1 = 0;

public int n2 = 0;

public String str = NULL;

}

Serializes an instance of the above class into a file


The code is as follows:

MyObject obj = new MyObject ();

OBJ.N1 = 1;

Obj.n2 = 24;

Obj.str = "some strings";

IFormatter formatter = new BinaryFormatter ();

Stream stream = new FileStream ("Myfile.bin", FileMode.Create,

FileAccess.Write, Fileshare.none);

Formatter. Serialize (stream, obj);

Stream. Close ();

Deserialization of the above instance


The code is as follows:

IFormatter formatter = new BinaryFormatter ();

Stream stream = new FileStream ("MyFile. Bin ", FileMode.Open,

FileAccess.Read, FileShare.Read);

MyObject obj = (MyObject) formatter. Deserialize (FromStream);

Stream. Close ();

If you require portability, use SoapFormatter. The changes you want to make are simply replacing the formatter in the above code with SoapFormatter, while the Serialize and deserialize calls do not change.

It is important to note that the Serializable property cannot be inherited. If a new class is derived from MyObject, the new class must also be marked with this property, otherwise it will not be serializable. For example, if you attempt to serialize the following class instance, a serializationexception is displayed, stating that the MyStuff type is not marked as serializable.


2. Selective serialization

A class typically contains fields that should not be serialized. For example, suppose a class uses a member variable to store the thread ID. When this class is deserialized, the thread that stores the ID stored when serializing this class may no longer run, so it makes no sense to serialize the value. You can prevent them from being serialized by using the NonSerialized property to tag member variables, as follows:


The code is as follows:

[Serializable]

public class MyObject

{

public int N1;

[NonSerialized]

public int n2;

Public String str;

}


3. Custom serialization

You can customize the serialization process by implementing the ISerializable interface on the object. This feature is especially useful when the value of a member variable is invalidated after deserialization, but you need to provide a value for the variable to reconstruct the full state of the object. To implement ISerializable, you need to implement the GetObjectData method and a special constructor that is used when deserializing the object. The following code example shows how to implement ISerializable on the MyObject class mentioned in the previous section.


The code is as follows:

[Serializable]

public class Myobject:iserializable

{

public int N1;

public int n2;

Public String str;

Public MyObject ()

{

}

Protected MyObject (SerializationInfo info, StreamingContext context)

{

N1 = info. GetInt32 ("I");

N2 = info. GetInt32 ("J");

str = info. GetString ("K");

}

public virtual void GetObjectData (SerializationInfo info,

StreamingContext context)

{

Info. AddValue ("I", N1);

Info. AddValue ("J", N2);

Info. AddValue ("K", str);

}

}

When calling GetObjectData during serialization, the SerializationInfo object provided in the method call needs to be populated. Simply add the variable that will be serialized in the form of a name/value pair. Its name can be any text. As long as the serialized data is sufficient to restore the object during deserialization, the member variables added to the SerializationInfo are freely selectable. If the base object implements ISerializable, the derived class should call the GetObjectData method of its base object.

It should be emphasized that when adding ISerializable to a class, you need to implement both GetObjectData and special constructors. If GetObjectData is missing, the compiler issues a warning. However, because constructors cannot be enforced, a warning is not issued when a constructor is missing. If you attempt to deserialize a class without a constructor, an exception will occur. The current design outperforms the setobjectdata approach in terms of eliminating potential security and versioning issues. For example, if the SetObjectData method is defined as part of an interface, this method must be a public method, which allows the user to write code to prevent multiple calls to the SetObjectData method. As you can imagine, if an object is performing certain operations and a malicious application calls the SetObjectData method of this object, it will cause some potential trouble.

During deserialization, SerializationInfo is passed to the class using a constructor provided for this purpose. When an object is deserialized, any visibility constraints on the constructor are ignored, so the class can be marked as public, protected, internal, or private. A good way to do this is to mark the constructor as protect in cases where the class is not encapsulated. If the class is encapsulated, it should be marked private. To restore the state of an object, simply retrieve the value of the variable from SerializationInfo by using the name that was used when serializing. If the base class implements ISerializable, the constructor of the base class should be called so that the underlying object can restore its variables.

If you derive a new class from a class that implements ISerializable, you must implement both the constructor and the GetObjectData method as long as the new class contains any variables that need to be serialized. The following code snippet shows how to do this using the MyObject class shown above.


The code is as follows:

[Serializable]

public class Objecttwo:myobject

{

public int num;

Public ObjectTwo (): Base ()

{

}

Protected ObjectTwo (SerializationInfo si, StreamingContext context):

Base (Si,context)

{

num = si. GetInt32 ("num");

}

public override void GetObjectData (SerializationInfo si,

StreamingContext context)

{

Base. GetObjectData (Si,context);

Si. AddValue ("num", num);

}

}

Remember to call the base class in the deserialization constructor, otherwise the constructors on the base class will never be called, and the complete object cannot be built after deserialization. It is very easy to retrieve keyword/value pairs during deserialization, but there are some problems when adding the objects back to the hash table because the classes derived from the hash list cannot be guaranteed to be deserialized. Therefore, it is recommended that you do not call methods on the hash table at this time.


Third, if the state of the object needs to change between different versions of the method

1, realize ISerializable. This allows you to precisely control the serialization and deserialization process and correctly add and interpret future states during deserialization.

2. Use the NonSerialized property to mark non-important member variables. This option is only available if the expected class changes between versions are small. For example, after you add a new variable to a higher version of a class, you can mark the variable as nonserialized to ensure that the class is compatible with earlier versions.

I hope this article is helpful to everyone's C # programming.

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
Serializable serialization examples in C #

This address: http://www.paobuke.com/develop/c-develop/pbk23336.html






Related Content C # A sample method of using FileStream to iterate through large file data C # uses a chained method to express the looping nesting of properties and properties in C # using a method that sets a program to run only once in C # programming
C # How to connect databases and update databases C # automatically determines the Excel version uses different connection strings C # to read system font color and size C # connection Operation MySQL DB instance (using official driver)

Serializable serialization examples in C #

Related Article

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.