建议56:使用继承ISerializable接口更灵活地控制序列化过程

接口ISerializable的意义在于,如果特性Serializable,以及与其像配套的OnDeserializedAttribute、OnDeserializingAttribute、OnSerializedAttribute、OnSerializingAttribute、NoSerializable等特性不能完全满足自定义序列化的要求,那就需要继承ISerializable了。

以下是格式化器的工作流程:如果格式化器在序列化一个对象的时候,发现对象继承了ISerializable接口,那它就会忽略掉类型所有的序列化特性,转而调用类型的GetObjectData方法来构造一个SerializationInfo对象,方法内部负责向这个对象添加所有需要序列化的字段(“添加”这个词可能不太恰当,因为我们在添加前可以随意处置这个字段)。以建议55中的例子为例,如果要为ChineseName构造对应的值,在类继承ISerializable接口的情况下,应该这样去实现:

    class Program
{
static void Main()
{
Person liming = new Person() { FirstName = "Ming", LastName = "Li" };
BinarySerializer.SerializeToFile(liming, @"c:\", "person.txt");
Person p = BinarySerializer.DeserializeFromFile<Person>(@"c:\person.txt");
Console.WriteLine(p.FirstName);
Console.WriteLine(p.LastName);
Console.WriteLine(p.ChineseName);
}
} [Serializable]
public class Person : ISerializable
{
public string FirstName;
public string LastName;
public string ChineseName; public Person()
{
} protected Person(SerializationInfo info, StreamingContext context)
{
FirstName = info.GetString("FirstName");
LastName = info.GetString("LastName");
ChineseName = string.Format("{0} {1}", LastName, FirstName);
} void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("FirstName", FirstName);
info.AddValue("LastName", LastName);
}
}

序列化工具类:

    public class BinarySerializer
{
//将类型序列化为字符串
public static string Serialize<T>(T t)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, t);
return System.Text.Encoding.UTF8.GetString(stream.ToArray());
}
} //将类型序列化为文件
public static void SerializeToFile<T>(T t, string path, string fullName)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fullPath = Path.Combine(path, fullName);
using (FileStream stream = new FileStream(fullPath, FileMode.OpenOrCreate))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, t);
stream.Flush();
}
} //将字符串反序列化为类型
public static TResult Deserialize<TResult>(string s) where TResult : class
{
byte[] bs = System.Text.Encoding.UTF8.GetBytes(s);
using (MemoryStream stream = new MemoryStream(bs))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as TResult;
}
} //将文件反序列化为类型
public static TResult DeserializeFromFile<TResult>(string path) where TResult : class
{
using (FileStream stream = new FileStream(path, FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(stream) as TResult;
}
}
}

我们在方法GetObjectData中处理序列化,然后在一个带参数的构造方法中处理反序列化。虽然在接口中没有地方指出需要这样一个构造器,但这确实是需要的,除非我们序列化后不再打算把它反序列化回来。

这个例子不能表现出ISerializable接口比Serializable特性的优势,见下面的例子:

将Person序列化,然后在反序列化中将其变为另一个对象:PersonAnother类型对象。要实现这个功能,需要Person和PersonAnother都实现ISerializable接口,原来其实很简单,就是在Person类的GetObjectData方法中处理序列化,在PersonAnother的受保护构造方法中反序列化。

    class Program
{
static void Main()
{
Person liming = new Person() { FirstName = "Ming", LastName = "Li" };
BinarySerializer.SerializeToFile(liming, @"c:\", "person.txt");
PersonAnother p = BinarySerializer.DeserializeFromFile<PersonAnother>(@"c:\person.txt");
Console.WriteLine(p.Name);
}
} [Serializable]
class PersonAnother : ISerializable
{
public string Name { get; set; } protected PersonAnother(SerializationInfo info, StreamingContext context)
{
Name = info.GetString("Name");
} void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
}
} [Serializable]
public class Person : ISerializable
{
public string FirstName;
public string LastName;
public string ChineseName; public Person()
{
} protected Person(SerializationInfo info, StreamingContext context)
{
} void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.SetType(typeof(PersonAnother));
info.AddValue("Name", string.Format("{0} {1}", LastName, FirstName));
}
}

在Person类型的GetObjectData方法中,有句代码非常重要:

info.SetType(typeof(PersonAnother));

它负责告诉序列化器:我要被反序列化为PersonAnother。而类型PersonAnother则很简单,它甚至都不需要知道谁会被反序列化成它,它不需要做任何特殊处理。

ISerializable接口这个特性很重要,如果运用得当,在版本升级中,它能处理类型因为字段变化而带来的问题。

转自:《编写高质量代码改善C#程序的157个建议》陆敏技

编写高质量代码改善C#程序的157个建议——建议56:使用继承ISerializable接口更灵活地控制序列化过程的更多相关文章

  1. 【转】编写高质量代码改善C#程序的157个建议——建议56:使用继承ISerializable接口更灵活地控制序列化过程

    建议56:使用继承ISerializable接口更灵活地控制序列化过程 接口ISerializable的意义在于,如果特性Serializable,以及与其像配套的OnDeserializedAttr ...

  2. 编写高质量代码改善C#程序的157个建议

    1.使用StringBuilder或者使用string.Format("{0}{1}{2}{3}", a, b, c, d)拼接字符串. 2.使用默认转型方法,比如使用类型内置的P ...

  3. 编写高质量代码改善C#程序的157个建议[1-3]

    原文:编写高质量代码改善C#程序的157个建议[1-3] 前言 本文主要来学习记录前三个建议. 建议1.正确操作字符串 建议2.使用默认转型方法 建议3.区别对待强制转换与as和is 其中有很多需要理 ...

  4. 读书--编写高质量代码 改善C#程序的157个建议

    最近读了陆敏技写的一本书<<编写高质量代码  改善C#程序的157个建议>>书写的很好.我还看了他的博客http://www.cnblogs.com/luminji . 前面部 ...

  5. 编写高质量代码改善C#程序的157个建议——建议157:从写第一个界面开始,就进行自动化测试

    建议157:从写第一个界面开始,就进行自动化测试 如果说单元测试是白盒测试,那么自动化测试就是黑盒测试.黑盒测试要求捕捉界面上的控件句柄,并对其进行编码,以达到模拟人工操作的目的.具体的自动化测试请学 ...

  6. 编写高质量代码改善C#程序的157个建议——建议156:利用特性为应用程序提供多个版本

    建议156:利用特性为应用程序提供多个版本 基于如下理由,需要为应用程序提供多个版本: 应用程序有体验版和完整功能版. 应用程序在迭代过程中需要屏蔽一些不成熟的功能. 假设我们的应用程序共有两类功能: ...

  7. 编写高质量代码改善C#程序的157个建议——建议155:随生产代码一起提交单元测试代码

    建议155:随生产代码一起提交单元测试代码 首先提出一个问题:我们害怕修改代码吗?是否曾经无数次面对乱糟糟的代码,下决心进行重构,然后在一个月后的某个周一,却收到来自测试版的报告:新的版本,没有之前的 ...

  8. 编写高质量代码改善C#程序的157个建议——建议154:不要过度设计,在敏捷中体会重构的乐趣

    建议154:不要过度设计,在敏捷中体会重构的乐趣 有时候,我们不得不随时更改软件的设计: 如果项目是针对某个大型机构的,不同级别的软件使用者,会提出不同的需求,或者随着关键岗位人员的更替,需求也会随个 ...

  9. 编写高质量代码改善C#程序的157个建议——建议153:若抛出异常,则必须要注释

    建议153:若抛出异常,则必须要注释 有一种必须加注释的场景,即使异常.如果API抛出异常,则必须给出注释.调用者必须通过注释才能知道如何处理那些专有的异常.通常,即便良好的命名也不可能告诉我们方法会 ...

随机推荐

  1. 避免Android内存泄露

    摘自:http://blog.csdn.net/xyz_lmn/article/details/7108011 Android的应用被限制为最多占用16m的内存,至少在T-Mobile G1上是这样的 ...

  2. 手把手教你在Eclipse中使用CVS Branch功能

    Brach 的作用: 开发新版本的人员就基于 main trunk 工作,而 fix bug 的人员就基于 branch 工作. 一旦在 branch上将 Release_1_0的 bug修复了,我们 ...

  3. loadsh学习

    由Underscore与Lodash的差异引发的思考:http://ju.outofmemory.cn/entry/106512 JavaScript工具库之Lodash Underscore和Lod ...

  4. 参数化防SQL注入

    private void AddStudent(){ string strName =txtName.Text.Trim(); string strPwd = txtPwd.Text.Trim(); ...

  5. laravel 中间件学习

    http://blog.csdn.net/kwinh/article/details/56285204 http://blog.csdn.net/fationyyk/article/details/5 ...

  6. java实例三维空间求点之间的距离。。。。

    package com.b; public class Ponit { private double x; private double y; private double z; public Pon ...

  7. CP干货:手机游戏上线前需要准备什么

    转自:http://www.gamelook.com.cn/2015/09/229002 游戏研发完成后游戏该怎样推广?如何找渠道?推广时需要注意什么?下面给大家介绍一下具体流程,可能每个公司的上线流 ...

  8. MariaDB存在的问题

    MySQL与MariaDB对嵌套的查询语句当中的order by的处理方法不同.MySQL会忠实执行内层查询的排序子句,但是MariaDB会将这个order by去掉,理论依据就是关系理论 --- 一 ...

  9. php使用substr中文乱码问题

    周天的时候对网站 https://www.javasec.cn 进行bug修复和功能更新,其中遇到一个比较有意思的小问题: 问题: 网站的置顶推荐中,有文本略缩.但是无论怎么修改最后一个字符始终现实为 ...

  10. spring-boot restful put方式提交表单

    使用spring-boot 做接口,如果按restful的路由形式想使用put方式进行表单提交,第一个参数应该为文件参数,代码如下: @PutMapping("/http-put" ...