.NET serialization

xiaoxiao2021-03-06  17

.NET provides three sequence modes:

1.XML Serialize

2.soap serialize

3.Binary Serialize

The first sequence method is not able to serialize some types, such as havehtable; I mainly introduce two types of sequentialization

One. Soap Serialize

Using SOAPFORMATTER.SERIALIZE () implement serialization. SoApFamatter Under System.Runtime.Serialization.Formatters.SoAP namespace, you need to reference system.runtime.Serialization.Formatters.Runtime.Serialization.Formatters.soap.dll. It can serialize objects into XML.

For example to serialize the Myclass class

[Serializable]

Class myclass: iSerializable

{

Protected string _name; protected string_id;

Protected Hashtable FieldTyPe = New Hashtable ();

Public myclass (): base () {} public myclass (serializationIzationinfo si, streamingcontext context): base (si, context) {}

Public string name {get {return _name;}}

Public string id {get {return _id;}}

Public HashTable FieldTypehash {Get {Return this.fieldType;}}

Public void start ()

{

.........

}

}

In this class, the red portion must be there. Otherwise, an abnormality "must be labeled as serialization when serialization", "no constructor", etc.

Below is a serialization function, transform the object serial into String string output

public string SoapSerializer (object o) {// FileStream fs = new FileStream ( "DataFile.xml", FileMode.Create); Stream ms = new MemoryStream (); // Construct a SoapFormatter and use it to serialize the data to the stream SOAPFORMATTER formatter = new soapformatter (); try {formatter.serialize (ms, o); byte [] b = new byte [ms.length]; ms.position = 0; ms.read (b, 0, b.ley ); String s = convert.tobase64String (b); returnction (serializationException e) {console.writeline ("failed to serialize);" E.MESSAGE); throw;} finally {ms.close () }

}

The following is a deserialization function,

Public myclass deserialize (string returbtring) {

SOAPFORMATTER FORMATTER; MemoryStream ms = null; try {formatter = new soapformatter (); byte [] b = convert.FromBase64String (ReturnString);

ms = new MemoryStream (b); MyClass response = (MyClass) formatter.Deserialize (ms); return response;} catch (SerializationException e) {Console.WriteLine ( "Failed to deserialize Reason:." e.Message); throw Finally {ms.close ();

}

II. Binary Serialize and SOAPSERIALIZE are similar, change SOAPFORMATTER to binaryformatter, but use System.Runtime.Serialization.Formatters.Binary namespace.

转载请注明原文地址:https://www.9cbs.com/read-45187.html

New Post(0)