serialization - C# testable serialize class -
i have big solution many count of serializers/deserializers +interfaces. i'd reduce files count keep testability , readability of code. i'm searching serializer provider (not factory), example:
interface iserializable { string serialize<t>(t obj); t deserialize<t>(string xml); } class serializable : iserializable { public string serialize<t>(t obj) { return this.toxml(obj); } public t deserialize<t>(string xml) { throw new system.notimplementedexception(); } } internal static class serializers { public static string toxml(this serializable s, int value) { } public static string toxml(this serializable s, sometype value) { } }
in case i'll need add new extension serialize type. common interface stay:
iserializable provider; provider.serialize<sometype>(obj);
using system; using system.io; namespace consoleapplication2 { using system.runtime.serialization; using system.xml; public interface iserializable { void serialize<t>(t obj, string xmlfile); t deserialize<t>(string xmlfile); } public class serializable : iserializable { public void serialize<t>(t obj, string xmlfile) { stream xmlstream = null; try { xmlstream = new memorystream(); var dcserializer = new datacontractserializer(typeof(t)); dcserializer.writeobject(xmlstream, obj); xmlstream.position = 0; // todo save file here use datacontract } catch (exception e) { throw new xmlexception("xml error", e); } { if (xmlstream != null) { xmlstream.close(); } } } public t deserialize<t>(string xmlfile) { filestream fs = null; try { fs = new filestream(xmlfile, filemode.open, fileaccess.read, fileshare.readwrite); if (fs.canseek) { fs.position = 0; } var dcserializer = new datacontractserializer(typeof(t)); var value = (t)dcserializer.readobject(fs); fs.close(); return value; } catch (exception e) { throw new xmlexception("xml error", e); } { if (fs != null) { fs.close(); } } } } [datacontract] public class { [datamember] public int test { get; set; } } public class test { public test() { var = new { test = 25 }; var ser = new serializable(); ser.serialize(a, "c:\\test.xml"); var a2 = ser.deserialize<a>("c:\test.xml"); if (a2.test == a.test) console.writeline("done"); } }
Comments
Post a Comment