zoukankan      html  css  js  c++  java
  • 二进制序列化

    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。此格式化程序为上面使用的示例生成以下输出。
        }

  • 相关阅读:
    2017-2018-1 20155208 20155212 20155239 实验一 开发环境的熟悉
    2017-2018-1 20155332实验三 实时系统报告
    2017-2018-1 20155332 《信息安全系统设计基础》第九周学习总结
    第9周 实现PWD命令
    2016-2017第一学期 20155332 第八周课堂实践
    2017-2018-1 20155312 《信息安全系统设计基础》第八周学习总结
    20155332实验二 固件编程
    2017-2018-1 20155332 《信息安全系统设计基础》第7周学习总结
    20155332口令破解实验
    2017-2018-1 20155332 《信息安全系统设计基础》第六周学习总结
  • 原文地址:https://www.cnblogs.com/yidianfeng/p/1372372.html
Copyright © 2011-2022 走看看