现在的位置: 首页 > 综合 > 正文

.NET序列化

2013年10月02日 ⁄ 综合 ⁄ 共 2024字 ⁄ 字号 评论关闭

.net提供了三种序列化方式:

1.XML Serialize

2.Soap Serialize

3.Binary Serialize

第一种序列化方式对有些类型不能够序列化,如hashtable;我主要介绍后两种类型得序列化

一.Soap Serialize

使用SoapFormatter.Serialize()实现序列化.SoapFamatter在System.Runtime.Serialization.Formatters.Soap命名空间下,使用时需要引用System.Runtime.Serialization.Formatters.Soap.dll.它可将对象序列化成xml.

比如要序列化MyClass类

[Serializable]

class MyClass:ISerializable

{

  protected string _name;
  protected string _id;

  protected Hashtable fieldtype=new Hashtable();

     public MyClass():base(){  }
     public MyClass(SerializationInfo 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()

{

   .........

}

}

在这个类中,红色部分为必须有的.否则在序列化此类的时候会产生异常“必须被标注为可序列化“,“没有构造函数“等...

下面是序列化函数,将对象序列化后转化成string字符串输出

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.Length);
               
    string s=Convert.ToBase64String(b);
    return s;
   }
   catch (SerializationException e)
   {
    Console.WriteLine("Failed to serialize. Reason: " + e.Message);
    throw;
   }
   finally
   {
    ms.Close();
   }

  }

下面是反序列化函数,

public MyClass Deserialize(string returnString)
  {

    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();
    
   }

  }

二.Binary Serialize和SoapSerialize类似,将SoapFormatter改成BinaryFormatter即可,但要使用System.Runtime.Serialization.Formatters.Binary命名空间.

抱歉!评论已关闭.