栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

本文实例讲述了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+"
"); Response.Write("n2: {0}" + obj.n2 + "
"); Response.Write("str: {0}" + obj.str + "
"); } //上面所用的 BinaryFormatter 非常有效,生成了非常简洁的字节流。 //通过该格式化程序序列化的所有对象也可以通过该格式化程序进行反序列化,这使该工具对于序列化将在 .NET framework 上被反序列化的对象而言十分理想。 //需要特别注意的是,在反序列化一个对象时不调用构造函数。出于性能方面的原因对反序列化施加了该约束。 //但是,这违反了运行库与对象编写器之间的一些通常约定,开发人员应确保他们在将对象标记为可序列化时了解其后果。 //如果可移植性是必需的,则转为使用 SoapFormatter。 //只需用 SoapFormatter 代替上面代码中的 BinaryFormatter, //并且如前面一样调用 Serialize 和 Deserialize。此格式化程序为上面使用的示例生成以下输出。 } }

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/125264.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号