可以交替使用BinaryFormatter和XmlSerializer [英] Using BinaryFormatter and XmlSerializer interchangeably

查看:98
本文介绍了可以交替使用BinaryFormatter和XmlSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了使用BinaryFormatter进行序列化的大量代码,现在我需要对其进行调试.当前所有的序列化代码都需要一个IFormatter.

I've inherited a large amount of code that uses BinaryFormatter for serialization, that I now need to debug. All the serialization code currently expects an IFormatter.

我有个想法,用XmlSerializer替换BinaryFormatter,使检查序列化的输出更容易,但是它们不兼容(没有通用的库或接口).

I had a idea to replace the BinaryFormatter with an XmlSerializer, to make examining the serialized output easier, but they aren't compatible (no common base or interface).

有没有一种标准的方法,例如使参数成为我的代码可以使用的某种通用序列化程序?理想情况下,我想在顶层创建我想要的任何具体序列化器,然后将其传递给下层而无需底层知道具体类型.

Is there a standard approach to this e.g. make the parameter some kind of generic serializer that my code can use? Ideally I'd like to create whichever concrete serializer I want at the top level, and then it pass it down without the lower levels needing to know the concrete type.

我目前拥有的示例:

BinaryFormatter bformatter = new BinaryFormatter();     //create a binary formatter
PutPw(bformatter, stream, panel.DevicePassword);    //encode and stream the password

public static void PutPw(IFormatter bf, Stream stream, string pw)
{
    ...
    bf.Serialize(stream, pw);
}

推荐答案

正如已经指出的那样,并非所有二进制可序列化的对象也都是XML可序列化的(例如,带有TimeSpan的任何对象).

As has already been pointed out, not all objects that are binary serializable, are also XML serializable (for example, anything with TimeSpan).

但是,如果您可以解决这个相当严重的缺陷,那么我可能会采用的方法是创建自己的界面.然后,我将有2个类来实现它,一类包装二进制格式器,一类包装XML序列化器.为了使生活更轻松,就应用程序使用的方法名称和参数而言,使接口与二进制格式化程序非常相似,以便可以相对轻松地替换出现的具体二进制格式化程序.

But if you can deal with that pretty serious flaw, then the approach I would probably take is to create my own interface. I would then have 2 classes that implement it, one wrapping the binary formatter and one wrapping the XML serializer. To make life easier, have the interface very similar to the binary formatter in terms of method names your app uses and parameters so that you can replace occurrences of the concrete binary formatter relatively painlessly.

这篇关于可以交替使用BinaryFormatter和XmlSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆