当前位置: 移动技术网 > IT编程>开发语言>c# > C#二进制序列化实例分析

C#二进制序列化实例分析

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#二进制序列化的方法。分享给大家供大家参考。具体如下:

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

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网