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

    技术2022-05-19  23

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

     

    using System;using System.Runtime.Serialization;using System.Runtime.Serialization.Formatters.Binary;using System.IO;

    /// <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();             formatter.Serialize(stream, obj);             stream.Position = 0;             byte[] buffer = new byte[stream.Length];             stream.Read(buffer, 0, buffer.Length);             stream.Flush();             stream.Close();             return Convert.ToBase64String(buffer);         }         catch (Exception ex)         {             throw new Exception("序列化失败,原因:" + ex.Message);         }     }

         /// <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)formatter.Deserialize(stream);             stream.Flush();             stream.Close();         }         catch (Exception ex)         {             throw new Exception("反序列化失败,原因:" + ex.Message);         }         return obj;     }

    }

     

    demo页面的cs文件代码:

    using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;

    public partial class _fan_xuliehua : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        //序列化        DataTable dt = new DataTable();        dt.Columns.Add("ID");        dt.Columns.Add("Name");        dt.Rows.Add(new object[] { 1, "first" });        dt.Rows.Add(new object[] { 2, "second" });        string result = SerializeUtilities.Serialize(dt);        Response.Write(result);               //反序列化        string mystr = result;        DataTable _resDT = new DataTable();

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

        }}


    最新回复(0)