实体类的二进制序列化
在.NET中,我们可以将对象序列化从而保存对象的状态到内存或者磁盘文件中,或者分布式应用程序中用于系统通信,一般来说,二进制序列化的效率要高,所获得的字节数最小,我们来看看下面的例子:
private static void Main(string[] args)
{
MemoryStream ms = null;
Customer customer = Customer.GetOneCustomer();
using (ms = new MemoryStream())
{
var formater = new BinaryFormatter();
formater.Serialize(ms, customer);
Console.WriteLine("BinaryFormatter Length:{0}", ms.Length);
}
using (ms = new MemoryStream())
{
var serializer = new XmlSerializer(typeof (Customer));
serializer.Serialize(ms, customer);
Console.WriteLine("XmlSerializer Length:{0}", ms.Length);
}
{
MemoryStream ms = null;
Customer customer = Customer.GetOneCustomer();
using (ms = new MemoryStream())
{
var formater = new BinaryFormatter();
formater.Serialize(ms, customer);
Console.WriteLine("BinaryFormatter Length:{0}", ms.Length);
}
using (ms = new MemoryStream())
{
var serializer = new XmlSerializer(typeof (Customer));
serializer.Serialize(ms, customer);
Console.WriteLine("XmlSerializer Length:{0}", ms.Length);
}
PDF.NET(PWMIS数据开发框架)的实体类也提供了二进制序列化功能,下面我们来演示一下它的使用:
//PDF.NET 实体类序列化、反序列化测试
Customer customer = new Customer();
customer.CustomerBirthday = new DateTime(1999, 1, 1);
customer.CustomerName = "张三";
customer.CustomerMobile = "13011111111";
//序列化
byte[] buffer= PdfNetSerialize.BinarySerialize(customer);
string tempString= Convert.ToBase64String(buffer);
Customer customer = new Customer();
customer.CustomerBirthday = new DateTime(1999, 1, 1);
customer.CustomerName = "张三";
customer.CustomerMobile = "13011111111";
//序列化
byte[] buffer= PdfNetSerialize.BinarySerialize(customer);
string tempString= Convert.ToBase64String(buffer);
//反序列化
byte[] buffer2 = Convert.FromBase64String(tempString);
//WFT_Customer customer2=(WFT_Customer) PdfNetSerialize.BinaryDeserialize(buffer2, typeof(WFT_Customer));
Customer customer2 = GetEntity<Customer>(buffer2);
byte[] buffer2 = Convert.FromBase64String(tempString);
//WFT_Customer customer2=(WFT_Customer) PdfNetSerialize.BinaryDeserialize(buffer2, typeof(WFT_Customer));
Customer customer2 = GetEntity<Customer>(buffer2);
上面的例子使用了Base64来将序列化后的字节数组转换成字符串,从而利于使用。如果想将二进制字节数组转直接换成字符串,可以使用具有8位编码的字符集转换,但不能使用其它字符集,比如Unicode、GB2312.
public string ConvertToString(object targetObject){
//ISO8859-1 字符串,8位,只有这种可以完整保留二进制
Encoding _encoding = Encoding.GetEncoding(28591);
byte[] buffer= PdfNetSerialize.BinarySerialize((EntityBase)targetObject);
return _encoding.GetString(buffer);
}
//ISO8859-1 字符串,8位,只有这种可以完整保留二进制
Encoding _encoding = Encoding.GetEncoding(28591);
byte[] buffer= PdfNetSerialize.BinarySerialize((EntityBase)targetObject);
return _encoding.GetString(buffer);
}
为了更通用,定义了一个GetEntity泛型方法,从二进制字节流反序列化获得一个实体类:
T GetEntity<T>(byte[] buffer ) where T:EntityBase
{
return (T)PdfNetSerialize.BinaryDeserialize(buffer, typeof(T));
}
{
return (T)PdfNetSerialize.BinaryDeserialize(buffer, typeof(T));
}
所以,PDF.NET框架的序列化功能使用很简单,而且也有很高的效率。利用二进制序列化,可以将一个实体对象集合持久化到磁盘,这样就有可能做出一个“对象数据库”了。