开发者

Do I really need to write this "SerializationHelper"?

I just wrote this SerializationHelper class, but I can't believe this is necessary!

using System.IO;
using System.Xml.Serialization;

public static class SerializationHelper
{
    public static string Serialize<T>(T obj)
    {
        var outStream = new StringWriter();
        var ser = new XmlSerializer(typeof(T));
        ser.Serialize(outStream, obj);
        return outStream.ToString();
    }

    public static T Deserialize<T>(string serialized)
    {
        var inStr开发者_如何学运维eam = new StringReader(serialized);
        var ser = new XmlSerializer(typeof(T));
        return (T)ser.Deserialize(inStream);
    }
}

And it's used like this:

var serialized = SerializationHelper.Serialize(myObj);

and:

var myObj = SerializationHelper.Deserialize<MyType>(serialized)

Am I missing something in the .NET framework? This is not rocket science!


In actual fact, the bits where you call the .NET API are these:

var ser = new XmlSerializer(typeof(T));
ser.Serialize(outStream, obj);

var ser = new XmlSerializer(typeof(T));
var obj = (T) ser.Deserialize(inStream);

The rest of the code is your personal specialisation. I don't think that two lines of code is too much for calling an API. You could always condense them, e.g.

(new XmlSerializer(typeof(T))).Serialize(outStream, obj);

var obj = (T) (new XmlSerializer(typeof(T))).Deserialize(inStream);

Purely as an aside, I should point out that I regard storing XML data in string variables as a Code Smell. As soon as you take XML data out of its raw binary form (XDocument, XmlDocument, XPathDocument or any other type of DOM), you run up against encoding issues. What if a developer serialises an object to a string with encoding X, then writes the string to a disk file with encoding Y? Not very safe. Besides which, if encoding X is not UTF-16, how would you even represent the data in a .NET string?


It's useful if you are doing any real amount (>1) of serialization/deserialization within a project. This was the case for me one time, so I just put a similar class in a Utils library, along with other reusable functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜