Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 1280 was 1280, checked in by epitzer, 15 years ago

Split classes into more files. (#506)

File size: 1.8 KB
Line 
1using System;
2using System.Collections;
3using System.Reflection;
4using System.Collections.Generic;
5namespace Persistence {
6
7  public interface ICustomSerializer {
8    bool CanSerialize(Type type);
9    IEnumerable Serialize(object o);
10    object DeSerialize(IEnumerable o, Type t);
11  }
12
13  public class EnumerableSerializer : ICustomSerializer {
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 : ICustomSerializer {
39
40    public bool CanSerialize(Type type) {
41      return type.IsArray;
42    }
43
44    public IEnumerable Serialize(object array) {
45      foreach (object o in (Array)array) {
46        yield return o;
47      }
48    }
49
50    public object DeSerialize(IEnumerable elements, Type t) {
51      List<object> allElements = new List<object>();
52      foreach (object obj in elements) {
53        allElements.Add(obj);
54      }
55      Array array =
56        Array.CreateInstance(t.GetElementType(), allElements.Count);
57      for (int i = 0; i < array.Length; i++) {
58        array.SetValue(allElements[i], i);
59      }
60      return array;
61    }
62
63  }
64
65
66}
Note: See TracBrowser for help on using the repository browser.