Ignore:
Timestamp:
03/09/09 15:16:14 (11 years ago)
Author:
epitzer
Message:

added compound serializers for KeyValuePair and Dictionary. (#506)

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/New Persistence Exploration/Persistence/Persistence/CompoundSerializers.cs

    r1314 r1316  
    3737
    3838  public class ArraySerializer : ICompoundSerializer {
    39 
    4039    public bool CanSerialize(Type type) {     
    4140      return type.IsArray;
    4241    }
    43 
    4442    public IEnumerable Serialize(object array) {
    4543      Array a = (Array)array;
     
    5250      }
    5351    }
    54 
    5552    public object DeSerialize(IEnumerable elements, Type t) {
    5653      IEnumerator e = elements.GetEnumerator();
     
    7875      return a;
    7976    }
    80 
    8177  }
    8278
     79  public class KeyValuePair2XmlSerializer : ICompoundSerializer {   
     80    public bool CanSerialize(Type type) {
     81      return type.IsGenericType &&
     82        type.GetGenericTypeDefinition().Name == "KeyValuePair`2";
     83    }
     84    public IEnumerable Serialize(object o) {     
     85      Type t = o.GetType();
     86      yield return t.GetProperty("Key").GetValue(o, null);
     87      yield return t.GetProperty("Value").GetValue(o, null);
     88    }
     89    public object DeSerialize(IEnumerable o, Type t) {
     90      return Activator.CreateInstance(t,
     91        new List<object>((IEnumerable<object>)o).ToArray());
     92    }   
     93  }
     94
     95  public class Dictionary2XmlSerializer : ICompoundSerializer {
     96    public bool CanSerialize(Type type) {
     97      return type.GetInterface("IDictionary") != null;       
     98    }
     99    public IEnumerable Serialize(object o) {
     100      IDictionary dict = (IDictionary)o;     
     101      foreach ( DictionaryEntry entry in dict) {
     102        yield return entry.Key;
     103        yield return entry.Value;
     104      }
     105    }
     106    public object DeSerialize(IEnumerable o, Type t) {
     107      IDictionary dict = (IDictionary)Activator.CreateInstance(t);
     108      IEnumerator iter = o.GetEnumerator();
     109      while (iter.MoveNext()) {
     110        object key = iter.Current;
     111        iter.MoveNext();
     112        object value = iter.Current;
     113        dict.Add(key, value);
     114      }
     115      return dict;
     116    }
     117  }
    83118
    84119}
Note: See TracChangeset for help on using the changeset viewer.