对象通常都有状态(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. [转]Sql Server 2005中的架构(Schema)、用户(User)、登录(Login)和角色(Role)

    每一个概念的产生必然是因为碰到了无法解决的问题.换句话说,如果没有它,必然会导致某些问题难以解决.所以我想从这个角度切入,希望能把这几个复杂而暧昧的多角关系从最实用的角度来阐述清楚. 在问题的最初,我 ...

  2. silverlight 双坐标轴

    public void CreateLine(Grid oGrid, string sTitle, string sTableName, bool ifGetSig, string sYUint, s ...

  3. iOS图片设置圆角

    一般我们在iOS开发的过程中设置圆角都是如下这样设置的. imageView.clipsToBounds = YES; [imageView.layer setCornerRadius:]; 这样设置 ...

  4. JSON对象与JSON数组的长度和遍历方法

    JSON对象与JSON数组的长度和遍历方法         1.json对象的长度与遍历                 结构:var json={“name”:”sm”,”sex”:”woman”} ...

  5. Scala学习笔记--抽象成员

    package com.evor.test1 class Test1 { } object Test1{ def main(args:Array[String]):Unit = { //类参数和抽象字 ...

  6. 给config加密

    Configuration config = WebConfigurationManager.OpenWebConfiguration("/"); ConfigurationSec ...

  7. Seafile的手册

    http://manual.seafile.com/http://manual-cn.seafile.com/deploy/using_mysql.html 中文版http://manual-cn.s ...

  8. linux awk 使用

    awk是linux下的一个命令,他对其他命令的输出,对文件的处理都十分强大,其实他更像一门编程语言,他可以自定义变量,有条件语句,有循环,有数组,有正则,有函数等.他读取输出,或者文件的方式是一行,一 ...

  9. C# 知识点收集

    1. 数组复制 byte[] source; byte[] dest; int srcOffset = 0; int dstOffset = 0; int count = 10; System.Buf ...

  10. MVC 增加统一异常处理机制

    原文地址:http://www.cnblogs.com/leoo2sk/archive/2008/11/05/1326655.html 摘要      本文将对“MVC公告发布系统”的发布公告功能添加 ...