c# - How can I serialize a tuple containing a basic type and an array of a basic type? -


in c# 4.0, i'm trying serialize , deserialize tuple<guid, int[]> using datacontractserializer. i've serialized , deserialized type guid, type int[] , type tuple<guid, int>. if try serialize type tuple<guid, int[]>, compiles, following runtime exception:

type 'system.int32[]' data contract name  'arrayofint:http://schemas.microsoft.com/2003/10/serialization/arrays' not expected. consider using datacontractresolver or add types not known statically list of known types - example, using knowntypeattribute attribute or adding them list of known  types passed datacontractserializer. 

my serialization , deserialization routines simple:

public static string serialize<t>(this t obj) {     var serializer = new datacontractserializer(obj.gettype());     using (var writer = new stringwriter())     using (var stm = new xmltextwriter(writer))     {         serializer.writeobject(stm, obj);         return writer.tostring();     } }  public static t deserialize<t>(this string serialized) {     var serializer = new datacontractserializer(typeof(t));     using (var reader = new stringreader(serialized))     using (var stm = new xmltextreader(reader))     {         return (t)serializer.readobject(stm);     } } 

why getting exception, , can resolve or around it? seem me tuple containing types can serialized should have no trouble being serialized.

how this?

class program {     public static class datacontractserializerfactory<t>     {         private static ienumerable<type> gettypearguments(type t, ienumerable<type> values)         {             if (t.isgenerictype)                 foreach (var arg in t.getgenericarguments())                     values = values.union(gettypearguments(arg, values));             else                 values = values.union(new[] { t });             return values;         }          public static datacontractserializer create()         {             return new datacontractserializer(typeof(t), gettypearguments(typeof(t), new[] { typeof(t) }));         }     }      static void main(string[] args)     {         var x = tuple.create(guid.newguid(), new[] { 1, 2, 3, 4, 5, 6 });          var serializer = datacontractserializerfactory<tuple<guid, int[]>>.create();          var sb = new stringbuilder();         using (var writer = xmlwriter.create(sb))         {             serializer.writeobject(writer, x);             writer.flush();             console.writeline(sb.tostring());         }     } } 

edit: ought work nested generic. base type , leaf type arguments considered. should easy if want in-between containers part of knowntypes too.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -