c# 实现类的序列化与反序列化 可保存于session viewstate cookie各种缓存中
来源:互联网 发布:nodejs获取windows ip 编辑:程序博客网 时间:2024/05/28 04:52
/// <summary>/// 序列化与反序列化类,支持中文/// </summary>public static class Serializer{//序列化类 public static string SerializeObject<T>(T obj) { System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); string result = string.Empty; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { bf.Serialize(ms, obj); byte[] byt = new byte[ms.Length]; byt = ms.ToArray(); result = System.Convert.ToBase64String(byt); ms.Flush(); } return result; }//反序列化类 public static T DeserializeObject<T>(string str) { T obj; System.Runtime.Serialization.IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); byte[] byt = Convert.FromBase64String(str); using (System.IO.MemoryStream ms = new System.IO.MemoryStream(byt, 0, byt.Length)) { obj = (T)bf.Deserialize(ms); } return obj; }}