Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/Persistence/CompoundSerializers.cs @ 1314

Last change on this file since 1314 was 1314, checked in by epitzer, 16 years ago

rename ICustomSerializer to ICompoundSerializer. (#506)

File size: 2.3 KB
Line 
1using System;
2using System.Collections;
3using System.Reflection;
4using System.Collections.Generic;
5namespace Persistence {
6
7  public interface ICompoundSerializer {
8    bool CanSerialize(Type type);
9    IEnumerable Serialize(object o);
10    object DeSerialize(IEnumerable o, Type t);
11  }
12
13  public class EnumerableSerializer : ICompoundSerializer {
14    public bool CanSerialize(Type type) {
15      if (type.GetInterface("IEnumerable") == null)
16        return false;
17      if (type.GetMethod("GetEnumerator", new Type[] { }) == null)
18        return false;
19      MethodInfo addMethod = type.GetMethod("Add");
20      if (addMethod == null)
21        return false;
22      if (addMethod.GetParameters().Length != 1)
23        return false;
24      return true;
25    }
26    public IEnumerable Serialize(object o) {
27      return (IEnumerable)o;
28    }
29    public object DeSerialize(IEnumerable objects, Type t) {
30      object instance = Activator.CreateInstance(t);
31      foreach (object o in objects) {
32        t.GetMethod("Add").Invoke(instance, new object[] { o });
33      }
34      return instance;
35    }
36  }
37
38  public class ArraySerializer : ICompoundSerializer {
39
40    public bool CanSerialize(Type type) {     
41      return type.IsArray;
42    }
43
44    public IEnumerable Serialize(object array) {
45      Array a = (Array)array;
46      yield return a.Rank;
47      for (int i = 0; i < a.Rank; i++) {
48        yield return a.GetLength(i);
49      }
50      foreach (object o in (Array)array) {
51        yield return o;
52      }
53    }
54
55    public object DeSerialize(IEnumerable elements, Type t) {
56      IEnumerator e = elements.GetEnumerator();
57      e.MoveNext();
58      int rank = (int)e.Current;
59      int[] lengths = new int[rank];
60      for (int i = 0; i < rank; i++) {
61        e.MoveNext();
62        lengths[i] = (int)e.Current;
63      }
64      Array a = Array.CreateInstance(t.GetElementType(), lengths);     
65      int[] positions = new int[rank];
66      while (e.MoveNext()) {
67        a.SetValue(e.Current, positions);
68        positions[0] += 1;
69        for (int i = 0; i < rank-1; i++) {
70          if (positions[i] >= lengths[i]) {
71            positions[i] = 0;
72            positions[i + 1] += 1;
73          } else {
74            break;
75          }
76        }
77      }
78      return a;
79    }
80
81  }
82
83
84}
Note: See TracBrowser for help on using the repository browser.