最近写的东西和网络通信有关,Socket的Send方法只能传byte数组,这才用到了序列化和反序列化的问题。
首先需将类型声明为可序列化:
[Serializable]
public class Test { ... }
然后我是将序列化和反序列化的方法写成了静态方法。反正这俩方法就只是用的,基本可以当成是过程语言的函数来用。实现方式如下:
/// <summary>
/// 序列化
/// </summary>
/// <param >要序列化的对象</param>
/// <returns>数据缓冲区</returns>
public static byte[] Serialize(object obj)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
formatter.Serialize(stream, obj);
byte[] data = stream.GetBuffer();
return data;
}
/// <summary>
/// 反序列化
/// </summary>
/// <param >数据缓冲区</param>
/// <returns>对象</returns>
public static object Deserialize(byte[] data)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream stream = new System.IO.MemoryStream(data);
data = null;
Object obj = formatter.Deserialize(stream);
return obj;
}
最后调用这俩方法就OK了,C里面结构提什么的好象直接强制类型转一下就行了,这点上C#有点麻烦啊。
////////////////////////////////////////////////////////////////////////////////////////////////////////////
XML序列化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace RegexActivator
{
public class ExtendMethods
{
public static void Serial<T>(T[] items, string path)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T[]));
TextWriter writer = new StreamWriter(path);
try
{
xmlSerializer.Serialize(writer, items);
}
finally
{
writer.Close();
}
}
public static T[] Deserial<T>(string path)
{
if (!File.Exists(path)) return new T[0];
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T[]));
FileStream fs = new FileStream(path, FileMode.Open);
T[] items;
try
{
items = (T[])xmlSerializer.Deserialize(fs);
}
finally
{
fs.Close();
}
return items;
}
}
}