对象通常都有状态(state),从一个对象中抽取这种状态,不论是将它存储于某地,还是通过网络传送,这种抽取动作称为“将一个对象序列化”,而反向处理过程,从一个被序列化的状态重建一个对象即为反序列化。

序列化工作系由一个特定的格式化器(formatter)完成,每个格式化器都提供Serialize和Deserialize两个方法。当格式化器将某个对象序列化后,所得好结果被放入一个流(Stream)中,(所谓的流是字节序列的一个抽象概念)因此可以包容任何序列化格式。一对象被存储于一个流之中,对象的状态好久可以被存储于磁盘上(或者说被持久化(persistent))

对于一个可被序列化的类型,只需要给他表上[Serializable]特性,也可以只赋给某个特定的字段

NonSerialized 指明被标记的字段不可序列化

下面是自己练习的示例:

1.二进制序列化

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks; namespace SerializableTest
{
public class Program
{
static void Main(string[] args)
{
Goods good = new Goods();
good.name = "苹果";
good.price = ;
good.type = "水果"; string dir = System.AppDomain.CurrentDomain.BaseDirectory; //序列化
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(dir+"test.bin", FileMode.Create, FileAccess.Write);
formatter.Serialize(stream, good);
stream.Close();//必须关闭 //反序列化
IFormatter reformatter = new BinaryFormatter();
Stream filestream = new FileStream(dir+"test.bin", FileMode.Open, FileAccess.Read); //返回Object类型,必须强制转换
Goods newgood = (Goods)reformatter.Deserialize(filestream); Console.WriteLine(newgood.name);
Console.WriteLine(newgood.price);
Console.WriteLine(newgood.type);
Console.ReadLine(); }
} [Serializable]
public class Goods
{
/// <summary>
/// 名称
/// </summary>
public string name { get; set; } /// <summary>
/// 价格
/// </summary>
public double price { get; set; } /// <summary>
/// 分类
/// </summary>
public string type { get; set; }
}
}

上例使用二进制格式化器BinaryFormatter:System.Runtime.Serialization.Formatters.Binary;

注:Iformatter接口序列化对象时,只需要提供了Stream流对象就行了。将对象序列化到文件流(FileStream)、内存流(MemoryStream)、网络流(NetworkStream)都可以。

在测试 特新NonSerialized 时出现了点问题:“特性“NonSerialized”对此声明类型无效。它只对“field”声明有效

由于C#3.0 的新特性get/set访问器,在编译的时候,编译器会自动为你生成对应的私有变量,变量名自动生成。

因此考虑 直接显示声明私有属性 private int number,并标注[NonSerialized]特性。

运行结果:

2.XML序列化

XML序列化,对象被以XML格式保存,XML序列化常常用在Web服务项目里(最近的项目里看到有模块用到,所以自己学习一下)

System.Xml.Serialization命名空间:含有使用XML序列化所需要的类和功能

XmlSerializer类,提供序列化Serialeze()和反序列话Deserialize()方法。

XmlIgnore属性,让XmlSerializer类跳过不序列化的成员(XML序列化 Serializable和NoSerialized属性将被忽略,而是使用XmlIgnore属性,它的作用与NoSerialized类似)

例如:

/// <summary>
/// 分类
/// </summary>
[XmlIgnore]
public string type { get; set; }

 Goods good = new Goods();
good.name = "苹果";
good.price = ;
good.type = "水果";
good.Number = ; string dir = System.AppDomain.CurrentDomain.BaseDirectory; //序列化
XmlSerializer formatter = new XmlSerializer(typeof(Goods));
FileStream stream = new FileStream(dir + "test.bin", FileMode.Create, FileAccess.Write);
formatter.Serialize(stream, good);
stream.Close();//必须关闭 //反序列化
XmlSerializer reformatter = new XmlSerializer(typeof(Goods));
FileStream filestream = new FileStream(dir + "test.bin", FileMode.Open, FileAccess.Read); //返回Object类型,必须强制转换
Goods newgood = (Goods)reformatter.Deserialize(filestream); Console.WriteLine("名称:" + newgood.name);
Console.WriteLine("价格:" + newgood.price);
Console.WriteLine("种类:" + newgood.type);
Console.WriteLine("数量:" + newgood.Number);
Console.ReadLine();

持久化后的XML数据

<?xml version="1.0"?>
<Goods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<name>苹果</name>
<price></price>
<Number></Number>
</Goods>

可以发现加了[XmlIgnore]特性的type字段没有被序列化

注:public int Number被序列化了,private int number 没有被序列化,据说XML序列化 private类型字段不能被序列化,且元素的属性必须为读/写属性。

基础命名空间:序列化 System.Runtime.Serialization的更多相关文章

  1. 基础命名空间:序列化_自定义序列化 System.Runtime.Serialization

    (  (From Msdn) 自定义序列化是控制类型的序列化和反序列化的过程,通过控制序列化,可以确保序列化兼容性.换而言之,在不中断类型核心功能的情况下,可在类型的不同版本之间序列化和反序列化. 重 ...

  2. System.Runtime.Serialization.SerializationException”类型的未经处理的异常在 System.Runtime.Serialization.dll 中发生

    异常信息: “System.Runtime.Serialization.SerializationException”类型的未经处理的异常在 System.Runtime.Serialization. ...

  3. System.Runtime.Serialization.cs

    ylbtech-System.Runtime.Serialization.cs 允许对象控制其自己的序列化和反序列化过程. 1.返回顶部 1. #region 程序集 mscorlib, Versio ...

  4. 找不到方法:“Boolean System.Runtime.Serialization.DataContractAttribute.get_IsReference()”的解决办法

    找不到方法:“Boolean System.Runtime.Serialization.DataContractAttribute.get_IsReference()”.的解决办法站点发布后部署到了两 ...

  5. 重写成员“log4net.Util.ReadOnlyPropertiesDictionary.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)”时违反了继承安全性规则

    在.NET 4.0下使用最新版本的log4Net 1.2.10,会遇到下面这样的错误: 重写成员“log4net.Util.ReadOnlyPropertiesDictionary.GetObject ...

  6. 找不到System.Runtime.Serialization.Json的解决方案

    System.ServiceModel System.ServiceModel.Web System.Runtime.Serialization 三者均要添加引用

  7. 引用System.Runtime.Serialization.Json

    vs2012下,重新添加一次System.Runtime.Serialization的引用

  8. csharp:.net 3.5 using System.Runtime.Serialization.Json read json

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  9. C# Serialization performance in System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,Newtonsoft.Json.JsonConvert and System.Text.Json.JsonSerializer.Serialize

    In .net core 3.0 using System;using System.Collections.Generic;using System.Collections;using System ...

随机推荐

  1. CaseFile

    出处 http://tools.kali.org/information-gathering/casefile CaseFile is the little brother to Maltego. I ...

  2. 百度地图HTML接口

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  3. linux shell脚本连接oracle查询数据插入文件和日志文件中

    #!/bin/sh sqlplus "用户名/密码@数据库"<<EOF  或者只有一个库的 :sqlplus "用户名/密码"<<EOF ...

  4. mysql查询分组归类函数-group_concat,通常与group_by一起使用

    select a.`name`,group_concat(b.name SEPARATOR'.') as persons from `group` as a,`person` as b,`person ...

  5. javaWeb RSA加密使用

      加密算法在各个网站运用很平常,今天整理代码的时候看到了我们项目中运用了RSA加密,就了解了一下. 先简单说一下RSA加密算法原理,RSA算法基于一个十分简单的数论事实:将两个大质数相乘十分容易,但 ...

  6. hdu Intelligent IME

    算法:字典树 题意:手机9键拼音:2:abc  3:def 4:ghi 5:jkl 6:mno 7:pqrs 8:tuv 9:wxyz: 第一行读入一个T,代表测试组数: 之后输入两个整数n和m, 有 ...

  7. python进行base64编解码

    [转] 直接上代码 import base64 fin = open(r"D:\2.zip", "rb") fout = open(r"D:\2.x. ...

  8. mysql(mariadb)重装

    MariaDB是MySQL的一个分支,主要由开源社区进行维护和升级,而MySQL被Oracle收购以后,发展较慢.在CentOS 7的软件仓库中,将MySQL更替为了MariaDB.  Centos  ...

  9. javascript区分电脑与手机登陆

    <script language="javascript"> function checkMobile() { var pda_user_agent_list = ne ...

  10. CC2530定时器3的输入捕获中断

    CC2530定时器3的输入捕获中断 使用的是tim3的通道1的输入捕获P1_7口.//GPIO配置成复用功能,同时设置P1_7为输入.void irCaptureGpioInit(void){ P1S ...