对象通常都有状态(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. java equals 心得体会

    要记住最有用的一点: equals 在已经被系统定义好的类中 是已经被重写好了的 父类中的 equals方法是比较的两个对象是否指向同一引用 在被定义除了父类以外比较的是两个对象的内容 因此 人为定义 ...

  2. BZOJ 1001 狼抓兔子 (网络流最小割/平面图的对偶图的最短路)

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1001 算法讨论: 1.可以用最大流做,最大流等于最小割. 2.可以把这个图转化其对偶图,然 ...

  3. UVA 10790 How Many Points of Intersection?

      How Many Points of Intersection?  We have two rows. There are a dots on the top row and b dots on ...

  4. setTimeout与setInterval方法的区别

    setTimeout与setInterval方法的区别 setTimeout()用于设定在指定的时间之后执行对应的函数或代码.,在全局作用域下执行 setTimeout(code,time[,args ...

  5. ORACLE 数据库概述

    1,发展史: 1978年,Orcale诞生 1982年,Orcale3推出了,它是第一个能够运行在大型机和小型机上的关系型数据库 1997年,Orcale公司推出了基于java语言的Orcale8,并 ...

  6. Struts2中的get、set方法作用:

    Struts2中的get.set方法作用: 在Struts2中,客户端和服务器之间的数据传输全部要用到get.set方法:用set方法 ,可以将表单中的值存入Action类.通过Struts2.0标签 ...

  7. php的一些小笔记-文件函数(2)

    ---恢复内容开始--- copy 文件的复制 echo copy('test.php','test1.php'); 如果成功的返回true,反之返回false 如何在多层目录中复制文件呢?也就是根据 ...

  8. Unicode的解救方案 - Windows程序设计(SDK)002

    Unicode的解救方案 让编程改变世界 Change the world by program 内容节选: 早期的Windows也是使用ASCII字符集,ASCII好处多多,但ASCII的第一个字母 ...

  9. 管理Activity 用户在主界面按两次回退退出系统

    1:定义一个用于管理Activity的类. /* * 用于管理Activity */ public class SysApp extends Application{ private List< ...

  10. WiEngine+Eclipse+CDT+Sequoyah实现c++编程智能感知提示

    经过一段时间的摸索,我初步肯定自己基于WiEngine平台和C++开发跨Android/iPhone游戏的最佳(至少目前)环境为: Eclipse+CDT+Sequoyah 第一,JAVA代码调试技术 ...