You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.2 KiB
51 lines
1.2 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Runtime.Serialization.Formatters.Binary;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace PObject
|
|
{
|
|
public class PSerializer
|
|
{
|
|
public static byte[] Serialize(object obj)
|
|
{
|
|
if (obj == null)
|
|
return null;
|
|
|
|
Type t = obj.GetType();
|
|
if (!t.IsSerializable)
|
|
return null;
|
|
|
|
BinaryFormatter formatter = new BinaryFormatter();
|
|
|
|
byte[] buff = null;
|
|
using (MemoryStream ms = new MemoryStream())
|
|
{
|
|
formatter.Serialize(ms, obj);
|
|
buff = ms.ToArray();
|
|
}
|
|
|
|
return buff;
|
|
}
|
|
|
|
public static T Deserialize<T>(byte[] data)
|
|
{
|
|
if (data == null || data.Length < 1)
|
|
return default(T);
|
|
|
|
T deserialized = default(T);
|
|
BinaryFormatter formatter = new BinaryFormatter();
|
|
using (MemoryStream ms = new MemoryStream(data))
|
|
{
|
|
object obj = formatter.Deserialize(ms);
|
|
if (obj != null && obj is T)
|
|
deserialized = (T)obj;
|
|
}
|
|
|
|
return deserialized;
|
|
}
|
|
}
|
|
}
|
|
|