using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace WebApplication1.Serialize
{
public partial class Binary1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//二进制序列化不同于 XMLSerializer 类,后者只序列化公共字段。
protected void Button1_Click(object sender, EventArgs e)
{
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("C:/MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
}
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
}
protected void Button2_Click(object sender, EventArgs e)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("C:/MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject)formatter.Deserialize(stream);
stream.Close();
// Here's the proof.
Response.Write("n1: {0}"+ obj.n1+"<br/>");
Response.Write("n2: {0}" + obj.n2 + "<br/>");
Response.Write("str: {0}" + obj.str + "<br/>");
}
//上面所用的 BinaryFormatter 非常有效,生成了非常简洁的字节流。
//通过该格式化程序序列化的所有对象也可以通过该格式化程序进行反序列化,这使该工具对于序列化将在 .NET Framework 上被反序列化的对象而言十分理想。
//需要特别注意的是,在反序列化一个对象时不调用构造函数。出于性能方面的原因对反序列化施加了该约束。
//但是,这违反了运行库与对象编写器之间的一些通常约定,开发人员应确保他们在将对象标记为可序列化时了解其后果。
//如果可移植性是必需的,则转为使用 SoapFormatter。
//只需用 SoapFormatter 代替上面代码中的 BinaryFormatter,
//并且如前面一样调用 Serialize 和 Deserialize。此格式化程序为上面使用的示例生成以下输出。
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有