EvilZone
Programming and Scripting => .NET Framework => : xor May 19, 2015, 02:12:42 AM
-
public static class XmlSerializerExtensions
{
public static T LoadFromXml<T>(this Stream stream)
{
var type = typeof(T);
var serializer = new XmlSerializer(type);
return (T)serializer.Deserialize(stream);
}
public static void SaveToXml<T>(this Stream stream, T obj)
{
var type = typeof (T);
var serializer = new XmlSerializer(type);
serializer.Serialize(stream, obj);
}
}
-
I think I would overload SaveToXml() to serialize to a string and return that string. Has more cookies.
-
There's absolutely no safety behind these functions to check if the data is even serializable or not. You're missing out on a lot of useful functionality.
-
You're right ArkPhaze. Exception handling is to be done by the caller.
As for overloads, that's user preference.
This function builds upon Streams as a means of quickly reading / writing to File Systems, Memory, Network. It's by no means designed for production systems, though I don't see the inherent safety issues? So any enlightenment would be nice.
-- xor
-
I'm talking about taking on a similar TryParse() paradigm, and these 2 methods:
https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.candeserialize%28v=vs.110%29.aspx (https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.candeserialize%28v=vs.110%29.aspx)
https://msdn.microsoft.com/en-us/library/system.type.isserializable%28v=vs.110%29.aspx (https://msdn.microsoft.com/en-us/library/system.type.isserializable%28v=vs.110%29.aspx)
These should probably not be done on the caller side for best design.