码迷,mamicode.com
首页 > Windows程序 > 详细

C# 对象序列化 与反序列化 封装方法

时间:2015-03-13 10:38:19      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

    /// <summary>
    /// BinaryFormatter序列化
    /// </summary>
    /// <param name="item">对象</param>
    public static string ToBinary<T>(T item)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream())
        {
            formatter.Serialize(ms, item);
            ms.Position = 0;
            byte[] bytes = ms.ToArray();
            StringBuilder sb = new StringBuilder();
            foreach (byte bt in bytes)
            {
                sb.Append(string.Format("{0:X2}", bt));
            }
            return sb.ToString();
        }
    }

    /// <summary>
    /// BinaryFormatter反序列化
    /// </summary>
    /// <param name="str">字符串序列</param>
    public static T FromBinary<T>(string str)
    {
        int intLen = str.Length / 2;
        byte[] bytes = new byte[intLen];
        for (int i = 0; i < intLen; i++)
        {
            int ibyte = Convert.ToInt32(str.Substring(i * 2, 2), 16);
            bytes[i] = (byte)ibyte;
        }
        BinaryFormatter formatter = new BinaryFormatter();
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            return (T)formatter.Deserialize(ms);
        }
    }

 

C# 对象序列化 与反序列化 封装方法

标签:

原文地址:http://www.cnblogs.com/sdpdf/p/4334325.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!