using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Dscf.Global.Utils
{
public class ObjectUtils
{
/// <summary>
/// 对像转成 byte 数组
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static byte[] ObjectToByte(Object obj)
{
using (MemoryStream ms = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
return ms.GetBuffer();
}
}
/// <summary>
/// 把序列化的数组转成对像
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static Object ByteToObject(byte[] bytes)
{
using (MemoryStream ms = new MemoryStream(bytes))
{
IFormatter formatter = new BinaryFormatter();
Object obj = formatter.Deserialize(ms);
return obj;
}
}
/// <summary>
/// 克隆一个对像
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static T CloneObject<T>(T t)
{
byte[] bb = ObjectToByte(t);
object obj= ByteToObject(bb);
return (T)obj;
}
}
}