c#将对象序列化为字符串和将字符串反序列化为对象

时间:2025-03-27 14:38:49

开发中,页面间传值最长用到的是url显式传参,session,application和cookie传值等。对于复杂对象页面传值,如果不考虑性能影响的话,通常可以使用session或者application。那么页面间如何通过url传递复杂对象呢?正像标题说的那样,对象 -->字符串,然后在目标页面再将从url参数得到的(字符串-->对象)。这个过程可以用下面的代码来实现:

 

using System;
using ;
using ;
using ;

/// <summary>
///SerializeUtilities 的摘要说明
/// </summary>
public class SerializeUtilities
{
 public SerializeUtilities()
 {
  //
  //TODO: 在此处添加构造函数逻辑
  //
 }


    /// <summary>
     /// 序列化 对象到字符串
     /// </summary>
     /// <param name="obj">泛型对象</param>
     /// <returns>序列化后的字符串</returns>
     public static string Serialize<T>(T obj)
     {
         try
         {
             IFormatter formatter = new BinaryFormatter();
             MemoryStream stream = new MemoryStream();
             (stream, obj);
             = 0;
             byte[] buffer = new byte[];
             (buffer, 0, );
             ();
             ();
             return Convert.ToBase64String(buffer);
         }
         catch (Exception ex)
         {
             throw new Exception("序列化失败,原因:" + );
         }
     }

     /// <summary>
     /// 反序列化 字符串到对象
     /// </summary>
     /// <param name="obj">泛型对象</param>
     /// <param name="str">要转换为对象的字符串</param>
     /// <returns>反序列化出来的对象</returns>
     public static T Desrialize<T>(T obj, string str)
     {
         try
         {
             obj = default(T);
             IFormatter formatter = new BinaryFormatter();
             byte[] buffer = Convert.FromBase64String(str);
             MemoryStream stream = new MemoryStream(buffer);
             obj = (T)(stream);
             ();
             ();
         }
         catch (Exception ex)
         {
             throw new Exception("反序列化失败,原因:" + );
         }
         return obj;
     }

}

 

demo页面的cs文件代码:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

public partial class _fan_xuliehua :
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //序列化
        DataTable dt = new DataTable();
        ("ID");
        ("Name");
        (new object[] { 1, "first" });
        (new object[] { 2, "second" });
        string result = (dt);
        (result);
       
        //反序列化
        string mystr = result;
        DataTable _resDT = new DataTable();

        _resDT = (DataTable)(_resDT, mystr);
       
        ("<br>反序列化结果<br>" + _resDT.Rows[0][0].ToString() + ":" +_resDT.Rows[0][1].ToString() + "<br>");
        (_resDT.Rows[1][0].ToString() + ":" + _resDT.Rows[1][1].ToString() + "<br>");

    }
}