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

重要提示:在早于 .NET Framework 4 的版本中,部分受信任的程序集中自定义用户数据的序列化是使用 GetObjectDatamethod() 完成的。 从版本 4.0 开始,该方法将标记有 SecurityCriticalAttribute 特性,该特性阻止在部分受信任的程序集中执行。 若要解决此情况,请实现 ISafeSerializationData 接口)

实现方法:

通过自定义类实现接口ISerializable来实现,需要实现接口的GetObjectData方法,添加一个特殊的构造函数,这个构造函数的参数必须与GetObjectData方法的参数相同(在反序列化时调用),如果缺少GetObjectData,编译器会发出警告,但是,鉴于无法强制现实构造函数,如果不存在构造函数,则不会发出任何警告,但此时如果尝试对某个对象进行反序列化,将会发生异常。

ISerializable接口代码:

using System;
using System.Runtime.InteropServices;
using System.Security; namespace System.Runtime.Serialization
{
// 摘要:
// 允许对象控制其自己的序列化和反序列化过程。
[ComVisible(true)]
public interface ISerializable
{
// 摘要:
// 使用将目标对象序列化所需的数据填充 System.Runtime.Serialization.SerializationInfo。
//
// 参数:
// info:
// 要填充数据的 System.Runtime.Serialization.SerializationInfo。
//
// context:
// 此序列化的目标(请参见 System.Runtime.Serialization.StreamingContext)。
//
// 异常:
// System.Security.SecurityException:
// 调用方没有所要求的权限。
[SecurityCritical]
void GetObjectData(SerializationInfo info, StreamingContext context);
}
}

其中参数 info 用来存放将要序列化或反序列化的对象的数据

context 描述给定的序列化流的源和目标,并提供一个由调用方定义的附加上下文

自定义Goods类实现ISerializable接口

 [Serializable]
public class Goods:ISerializable
{
/// <summary>
/// 名称
/// </summary>
public string name { get; set; } /// <summary>
/// 价格
/// </summary>
public double price { get; set; } /// <summary>
/// 分类
/// </summary>
public string type { get; set; } public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("name", name);
info.AddValue("price", price);
//info.AddValue("type", type); //此属性不序列化
}
public Goods() { } //声明为私有的或受保护的,防止直接使用它
protected Goods(SerializationInfo info, StreamingContext context)
{
name = info.GetString("name");
price = info.GetDouble("price");
//type = info.GetString("type"); //此属性无法反序列化 } }

分析:在实现 GetObjectData 方法时,最常调用的SerializationInfo的方法是AddValue,这个方法具有针对所有标准类型(int、char等等)的重载版本,将待序列化变量以名称和值对的形式添加;(而 StreamingContext 参数描述给定的序列化流的源和目标,这样就可以知道是将对象序列化到持久性存储还是在将他们跨进程或机器序列化)。而在反序列化时,我们调用SerializationInfo提供的一组GetValue方法,他们针对所有标准类型数据执行各种AddValue重载版本的逆操作。

在要序列化的时候我们通过AddValue()方法往info中填充数据,序列化程序将保存在info中的数据进行序列化。

而当要反序列化的时候,我们从info中用GetValue()将数据取出,赋值给对应的属性

测试代码:

            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);
filestream.Close(); Console.WriteLine("名称:"+newgood.name);
Console.WriteLine("价格:"+newgood.price);
Console.WriteLine("类型:"+newgood.type);
Console.ReadLine();

运行结果:type属性没有序列化

参考 http://msdn.microsoft.com/zh-cn/library/ty01x675.aspx

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

  1. 基础命名空间:序列化 System.Runtime.Serialization

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

  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. 费马小定理&欧拉定理

    在p是素数的情况下,对任意整数x都有xp≡x(mod p).这个定理被称作费马小定理其中如果x无法被p整除,我们有xp-1≡1(mod p).利用这条性质,在p是素数的情况下,就很容易求出一个数的逆元 ...

  2. python文件批量改名

    python对文件进行批量改名用到的是os模块中的listdir方法和rename方法. os.listdir(dir)  :获取指定目录下的所有子目录和文件名 os.rename(原文件名,新文件名 ...

  3. 分治算法求乘方a^b 取余p(divide and conquer)

    传统的计算方法为循环n个a相乘.时间复杂度为O(n). 如用分治算法,效率可提升至O(lgn). 结合recursive有 double pow(int a, int n){ ) ; ) return ...

  4. 单片机(MCU)使用常用名字解释

    总线:指能为多个部件服务的信息传送线,在微机系统中各个部件通过总线相互通信. 地址总线(AB):地址总线是单向的,用于传送地址信息.地址总线的宽度为16位,因此基外部存储器直接寻址64K,16位地址总 ...

  5. 新版TeamTalk部署教程(蓝狐)

    http://www.bluefoxah.org/teamtalk/new_tt_deploy.html

  6. 猎豹上市(猎豹的广告收入中有70%来自BAT三家公司,总收入中有58%来自BAT)

    发表日期: 2014 年 5 月 9 日 From 网易专题 文/赵楠 村里那点儿事 猎豹移动上市之夜,我挺激动. 激动除了因为有好朋友在这家公司外,也因为猎豹移动在历史上的几次起承转合非常不易,在巨 ...

  7. 《Programming WPF》翻译 第3章 4.我们进行到哪里了?

    原文:<Programming WPF>翻译 第3章 4.我们进行到哪里了? 控件是由应用程序创建的块.它们描述了用户用来交互的界面特征.控件提供了行为,依赖样式和模板来表示一个外观.输入 ...

  8. linux查看系统版本和系统位数 (转)

    1. uname -ayou will view kernel name.network node hostname.kernel release.kernel version.machine har ...

  9. c++ 03

    一.面向对象编程 1.什么是对象?什么是对象编程? 1)万物皆对象 2)世界是由一组相互之间紧密联系的对象组成的. 3)通过将对象按照属性和行为共性进行分类,达到将具体事物进行抽象的效果. 4)通过程 ...

  10. 利用智能手机(Android)追踪一块磁铁(三)

    更新磁铁追踪算法的源代码,Android Studio项目工程 github地址:https://github.com/amazingyyc/MagnetLocate 说明:将磁铁的位置信息封装成消息 ...