下面是序列化与反序列化通用的方法:
序列化
/// <summary>
/// 序列化
/// </summary>
/// <typeparam name="T">要序列化的对象类型</typeparam>
/// <param name="file">序列化出来的文件</param>
/// <param name="tObj">要序列化的对象</param>
/// <returns></returns>
public static bool Serialize<T>(string file, T obj)
{
using (Stream stream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None))
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
return true;
}
}
/// <summary>
/// 序列化
/// </summary>
/// <typeparam name="T">要序列化的对象类型</typeparam>
/// <param name="file">序列化出来的文件</param>
/// <param name="tObj">要序列化的对象</param>
/// <returns></returns>
public static bool Serialize<T>(string file, T obj)
{
using (Stream stream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None))
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, obj);
return true;
}
}
反序列化
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T">反序列化出来对象类型</typeparam>
/// <param name="file">要反序列化的文件</param>
/// <returns></returns>
public static T Deserialize<T>(string file)
{
T obj = default(T);
using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
IFormatter formatter = new BinaryFormatter();
obj = (T)formatter.Deserialize(stream);
return obj;
}
}
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T">反序列化出来对象类型</typeparam>
/// <param name="file">要反序列化的文件</param>
/// <returns></returns>
public static T Deserialize<T>(string file)
{
T obj = default(T);
using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
IFormatter formatter = new BinaryFormatter();
obj = (T)formatter.Deserialize(stream);
return obj;
}
}