深入C#学习系列一:序列化(Serialize)、反序列化(Deserialize)

深入C#学习系列一:序列化(Serialize)、反序列化(Deserialize)

序列化又称串行化,是.NET运行时环境用来支持用户定义类型的流化的机制。其目的是以某种存储形成使自定义对象持久化,或者将这种对象从一个地方传输到另一个地方。
    .NET框架提供了两种串行化的方式:1、是使用BinaryFormatter进行串行化;2、使用SoapFormatter进行串行化;3、使用XmlSerializer进行串行化。第一种方式提供了一个简单的二进制数据流以及某些附加的类型信息,而第二种将数据流格式化为XML存储;第三种其实和第二种差不多也是XML的格式存储,只不过比第二种的XML格式要简化很多(去掉了SOAP特有的额外信息)。
    可以使用[Serializable]属性将类标志为可序列化的。如果某个类的元素不想被序列化,1、2可以使用[NonSerialized]属性来标志,2、可以使用[XmlIgnore]来标志。
    1、使用BinaryFormatter进行串行化
    下面是一个可串行化的类:
    
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using
 System.Runtime.Serialization.Formatters.Binary;
/**//// <summary>
/// ClassToSerialize 的摘要说明
/// </summary>

[Serializable]
public class ClassToSerialize
{
    
public int id = 100;
    
public string name = "Name";
    [NonSerialized]
    
public string Sex = "";
}


    下面是串行化和反串行化的方法:
    
public void SerializeNow()
    
{
        ClassToSerialize c 
= new ClassToSerialize();
        FileStream fileStream 
= new FileStream("c:\\temp.dat", FileMode.Create);
        BinaryFormatter b 
= new BinaryFormatter();
        b.Serialize(fileStream, c);
        fileStream.Close();
    }

    
public void DeSerializeNow()
    
{
        ClassToSerialize c 
= new ClassToSerialize();
        c.Sex 
= "kkkk";
        FileStream fileStream 
= new FileStream("c:\\temp.dat", FileMode.Open, FileAccess.Read, FileShare.Read);
        BinaryFormatter b 
= new BinaryFormatter();
        c 
= b.Deserialize(fileStream) as ClassToSerialize;
          Response.Write(c.name);
        Response.Write(c.Sex);
        fileStream.Close();
    }

    调用上述两个方法就可以看到串行化的结果:Sex属性因为被标志为[NonSerialized],故其值总是为null。
    2、使用SoapFormatter进行串行化
    和BinaryFormatter类似,我们只需要做一下简单修改即可:
    a.将using语句中的.Formatter.Binary改为.Formatter.Soap;
    b.将所有的BinaryFormatter替换为SoapFormatter.
    c.确保报存文件的扩展名为.xml
    经过上面简单改动,即可实现SoapFormatter的串行化,这时候产生的文件就是一个xml格式的文件。
    3、使用XmlSerializer进行串行化
    关于格式化器还有一个问题,假设我们需要XML,但是不想要SOAP特有的额外信息,那么我们应该怎么办呢?有两中方案:要么编写一个实现IFormatter接口的类,采用的方式类似于SoapFormatter类,但是没有你不需要的信息;要么使用库类XmlSerializer,这个类不使用Serializable属性,但是它提供了类似的功能。
    如果我们不想使用主流的串行化机制,而想使用XmlSeralizer进行串行化我们需要做一下修改:
    a.添加System.Xml.Serialization命名空间。
    b.Serializable和NoSerialized属性将被忽略,而是使用XmlIgnore属性,它的行为与NoSerialized类似。
    c.XmlSeralizer要求类有个默认的构造器,这个条件可能已经满足了。
    下面看示例:
    要序列化的类:
    
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Serialization;
[Serializable]
public class Person
{
    
private string name;
    
public string Name
    
{
        
get
        
{
            
return name;
        }

        
set
        
{
            name 
= value;
        }

    }



    
public string Sex;
    
public int Age = 31;
    
public Course[] Courses;

    
public Person()
    
{
    }

    
public Person(string Name)
    
{
        name 
= Name;
        Sex 
= "";
    }

}

[Serializable]
public class Course
{
    
public string Name;
    [XmlIgnore]
    
public string Description;
    
public Course()
    
{
    }

    
public Course(string name, string description)
    
{
        Name 
= name;
        Description 
= description;
    }

}
  

    序列化和反序列化方法:
public void XMLSerialize()
    
{
        Person c 
= new Person("cyj");
        c.Courses 
= new Course[2];
        c.Courses[
0= new Course("英语""交流工具");
        c.Courses[
1= new Course("数学","自然科学");
        XmlSerializer xs 
= new XmlSerializer(typeof(Person));
        Stream stream 
= new FileStream("c:\\cyj.XML",FileMode.Create,FileAccess.Write,FileShare.Read);
        xs.Serialize(stream,c);
        stream.Close();
    }

    
public void XMLDeserialize()
    
{
        XmlSerializer xs 
= new XmlSerializer(typeof(Person));
        Stream stream 
= new FileStream("C:\\cyj.XML",FileMode.Open,FileAccess.Read,FileShare.Read);
        Person p 
= xs.Deserialize(stream) as Person;
        Response.Write(p.Name);
        Response.Write(p.Age.ToString());
        Response.Write(p.Courses[
0].Name);
        Response.Write(p.Courses[
0].Description);
        Response.Write(p.Courses[
1].Name);
        Response.Write(p.Courses[
1].Description);
        stream.Close();
    }

这里Course类的Description属性值将始终为null,生成的xml文档中也没有该节点,如下图:
<?xml version="1.0"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  
<Sex></Sex>
  
<Age>31</Age>
  
<Courses>
    
<Course>
      
<Name>英语</Name>
      
<Description>交流工具</Description>
    
</Course>
    
<Course>
      
<Name>数学</Name>
      
<Description>自然科学</Description>
    
</Course>
  
</Courses>
  
<Name>cyj</Name>
</Person>

    4、自定义序列化
    如果你希望让用户对类进行串行化,但是对数据流的组织方式不完全满意,那么可以通过在自定义类中实现接口来自定义串行化行为。这个接口只有一个方法,GetObjectData. 这个方法用于将对类对象进行串行化所需要的数据填进SerializationInfo对象。你使用的格式化器将构造SerializationInfo对象,然后在串行化时调用GetObjectData. 如果类的父类也实现了ISerializable,那么应该调用GetObjectData的父类实现。
    如果你实现了ISerializable,那么还必须提供一个具有特定原型的构造器,这个构造器的参数列表必须与GetObjectData相同。这个构造器应该被声明为私有的或受保护的,以防止粗心的开发人员直接使用它。
    示例如下:
    实现ISerializable的类:
    
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
/**//// <summary>
/// Employee 的摘要说明
/// </summary>

[Serializable]
public class Employee:ISerializable
{
    
public int EmpId=100;
    
public string EmpName="刘德华";
    [NonSerialized]
    
public string NoSerialString = "NoSerialString-Test";
    
public Employee()
    
{
        
//
        
// TODO: 在此处添加构造函数逻辑
        
//
    }

    
private Employee(SerializationInfo info, StreamingContext ctxt)
    
{
        EmpId 
= (int)info.GetValue("EmployeeId"typeof(int));
        EmpName 
= (String)info.GetValue("EmployeeName",typeof(string));
        
//NoSerialString = (String)info.GetValue("EmployeeString",typeof(string));
    }

    
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
    
{
        info.AddValue(
"EmployeeId", EmpId);
        info.AddValue(
"EmployeeName", EmpName);
        
//info.AddValue("EmployeeString", NoSerialString);
    }

}


    序列化和反序列化方法:
public void OtherEmployeeClassTest()
    
{
        Employee mp 
= new Employee();
        mp.EmpId 
= 10;
        mp.EmpName 
= "邱枫";
        mp.NoSerialString 
= "你好呀";
        Stream steam 
= File.Open("c:\\temp3.dat", FileMode.Create);
        BinaryFormatter bf 
= new BinaryFormatter();
        Response.Write(
"Writing Employee Info:");
        bf.Serialize(steam,mp);
        steam.Close();
        mp 
= null;
        
//反序列化
        Stream steam2 = File.Open("c:\\temp3.dat", FileMode.Open);
        BinaryFormatter bf2 
= new BinaryFormatter();
        Response.Write(
"Reading Employee Info:");
        Employee mp2 
= (Employee)bf2.Deserialize(steam2);
        steam2.Close();
        Response.Write(mp2.EmpId);
        Response.Write(mp2.EmpName);
        Response.Write(mp2.NoSerialString);
    }

转载于:https://www.cnblogs.com/smallstupidwife/archive/2011/12/08/2280326.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/549737.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

分别用 数组和链表处理约瑟夫环问题

#include <stdio.h> #include <stdlib.h> int main() { int k0,n0,s0,m0; //k为1,2,3报数时的计数变量,m为退出人数 int num [100]; int *pnum; int i; printf("Enter the number of person and the key:"); scanf("%d%d",&n,…

QT_环境搭建

QT_环境搭建 Qt软件安装&#xff1a;https://www.jianshu.com/p/65bc892829a0 Qt软件下载&#xff1a;https://mirrors.tuna.tsinghua.edu.cn/qt/official_releases/qt/5.13/5.13.0/ 转载于:https://www.cnblogs.com/panda-w/p/11338742.html

十一月·飘·立冬

十一月的南粤叶依然青翠在枝头与秋风和舞落叶遍地的诗意画面在博客生活逝如流年 渐走渐淡回忆飘然而来又飘然而去秋的最后一天放下回忆 飘去天涯飘不要说也不要问目光交错的一瞬注定了今生缘分此情可以见真心春风急 秋风也狠乱乱纷纷 是红尘浮浮沉沉 似幻似真金枝玉叶的结…

OCP-052考试题库汇总(27)-CUUG内部解答版

Which two of these must be available READ/WRITE to keep a database open? A)all copies of the control file. B)the password file. C)all members of the current redo log group. D)spfile. E)TEMP tablespace F)SYSAUX tablespace Answer: AC 转载于:https://www.cnbl…

07/11/10 资料整理

脉码调制PMC T1 E1 T2 T32007-10-31 10:39什么是T1? 北美的24路脉码调制PCM简称T1&#xff0c;速率是1.544Mbit/s 我国采用的是欧洲的T1标准。北美使用的T1系统共有24个话路&#xff0c;每个话路采样脉冲用7bit编码&#xff0c;然后再加上1位信令码元&#xff0c;因此一个话路…

printf \r \n

简介 \r 回到这一行的开始处 \n 换下一行 参考链接 csdn 转载于:https://www.cnblogs.com/eat-too-much/p/11339935.html

真正的累

真正的累&#xff0c;是从骨头里泛出来的一丝丝的酸软&#xff0c;先是在后背盘旋&#xff0c;不痒也不痛&#xff0c;就是不舒服。然后身上热烘烘的&#xff0c;就着这热气&#xff0c;那些酸软就从后背发散开来。眼睛也会有点酸&#xff0c;闭上眼睛就会很舒服。你不得不挺直…

OCP-052考试题库汇总(28)-CUUG内部解答版

Archivelog mode is enabled for your database and DB_CREATE_FILE_DEST is set to ‘/u01/oracle/db01’. The parameters, DB_CREATE_ONLINE_LOG_DEST_n and DB_RECOVERY_FILE_DEST, and not specified. Which four are stored in the location specified by DB_CREATE_FILE…

Centos 系统安装NetCore SDK命令以及一系列操作(1)

17年买的jesse老师的课程&#xff0c;虽然说NetCore出来很久了&#xff0c;自己打入行的时候就奔它去的&#xff0c;但。。。。废话不说了&#xff0c;还是自己做了再说吧&#xff0c; 首先需要一个Centos系统来让我们开始玩&#xff0c;下载地址&#xff1a;https://www.cento…

如何高效地判断奇数和偶数

在我们日常的编程当中&#xff0c;常常会遇到判断某个整数属于奇数还是偶数的情况。 大家一般的处理做法是用这个整数和2取模。然后判断是等于1还是等于0。 这里&#xff0c;我要为大家介绍一种快速有效的判断做法&#xff0c;利用2进制进行判断。 大家都知道&#xff0c;奇数的…

百万分之一的新闻

昨天看到一则新闻&#xff0c;堪称罕见的新闻&#xff0c;百万分之一的新闻。 讲的是南京发生一件奇闻&#xff0c;一名女子生下一对双胞胎&#xff0c;竟然是同母异父的双胞胎。医学专家说这种概率是百万分之一。 新闻链接如下&#xff1a;http://bbs.people.com.cn/postDetai…

Windows Azure Traffic Manager (6) 使用Traffic Manager,实现本地应用+云端应用的高可用...

《Windows Azure Platform 系列文章目录》 注意&#xff1a;本文介绍的是使用国内由世纪互联运维的Azure China服务。 以前的Traffic Manager&#xff0c;背后的Service Endpoint必须是Azure数据中心的Cloud Service。 现在最新的Traffic Manager&#xff0c;Endpoint不仅仅支持…

Windows Azure Cloud Service (17) Role Endpoint

《Windows Azure Platform 系列文章目录》 在Windows Azure平台中&#xff0c;用户最多可以对以个Role指定5个Endpoint。而一个Hosted Service最多允许包含5个Role,所以说在一个Hosted Service中用户最多能定义25个Endpoint。 而对于每一个Endpoint&#xff0c;使用者需要设定如…

java打印一年中所有日期

public class Main { public static void main(String args[]) { //请注意月份是从0-11,天数是1&#xff0c; 2013-1-1 至 2013-12-31Calendar start Calendar.getInstance();start.set(2013, 0, 1); //2013-1-1 开始Calendar end Calendar.getInstance();end.set(20…

sentry + vue实现错误日志监控

起因 项目采用vue全家桶开发&#xff0c;现在拟嵌入sentry&#xff0c;实现对于线上网站进行错误日志记录。其实上传日志很简单&#xff0c;基本配置就可以了&#xff0c;但是上传配套的sourcemap则颇为费劲。这里记录一下使用心得。 实施步骤 上传日志 sentry使用文档&…

OSPF单域实验报告

1.1 实验任务<?xml:namespace prefix o ns "urn:schemas-microsoft-com:office:office" />(1) 配置Loopback地址作为路由器的ID。(2) 配置OSPF的进程并在相应的接口上启用。(3) OSPF起来后&#xff0c;更新计时器。1.2 实验环境和网络拓扑<?xm…

常用唤醒APP的方式

参考常用唤醒APP的方式

ASP.NET编程规范

第一部分&#xff1a;界面设计标准 1&#xff0e;开发环境设置&#xff1a;屏幕设置为800*600/1024*768 2&#xff0e;界面设计原则&#xff1a;风格必须统一 3&#xff0e;B/S结构开发原则&#xff1a;使用框架/模板 4&#xff0e;页面使用表格&#xff08;Table&#xff09;进…

H5页面适配iOS、Android和微信

前言 本文章针对H5开发的单页全屏无滚动页面。 解决方案 整体采用vw、vh作为基本单位&#xff0c;采用flex布局&#xff0c;针对字体使用rem单位。 多终端适配 针对app包下载等业务场景&#xff0c;需要识别对应的终端&#xff0c;采用不同的地址下载。针对微信特定情况&a…

代码随想录算法训练营第十三天 | 239. 滑动窗口最大值、347.前 K 个高频元素

239. 滑动窗口最大值 题目链接&#xff1a;239. 滑动窗口最大值 给你一个整数数组 nums&#xff0c;有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。 返回 滑动窗口中的最大值 。 文章讲解…