问题
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.
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.
Example of what I currently have:
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);
}
回答1:
As has already been pointed out, not all objects that are binary serializable, are also XML serializable (for example, anything with TimeSpan).
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.
回答2:
Have you checked SoapFormatter
? Not so readable like XmlSerializer but still XML, and you can understand most of the values. And it inherits from IFormatter, as BinaryFormatter does. So you can change to without need to touch your code.
And more, XmlSerializer can handle only public properties, of objects that have a parameterless constructor, while IFormatters work with reflection and can handle private fields and objects with a parameterized contructor. In addition the attribute Serializable
can work with formatters only and not with XmlSerializer. It's fundmentally different, and you might have to change a lot of code.
来源:https://stackoverflow.com/questions/13977538/using-binaryformatter-and-xmlserializer-interchangeably