.NET序列化

.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命名空间.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值