110,545
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 序列化对象
/// </summary>
/// <param name="obj">要序列化的对象</param>
/// <returns>对象的数据</returns>
public static byte[] Serialize(object obj)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(ms, obj);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
return ms.ToArray();
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="data">对象的数据</param>
/// <returns>解析的对象</returns>
public static object Deserialize(byte[] data)
{
object obj =null;
try
{
MemoryStream ms = new MemoryStream(data);
BinaryFormatter formatter = new BinaryFormatter();
obj = formatter.Deserialize(ms);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
return obj;
}
MemoryStream ms = new MemoryStream(data);
ms.Position=0
BinaryFormatter formatter = new BinaryFormatter();
obj = formatter.Deserialize(ms);