Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/Persistence/Default/Decomposers/KeyValuePairDecomposer.cs @ 1447

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

refactoring and code clean up. (#9999)

File size: 1.6 KB
Line 
1using System;
2using System.Linq;
3using System.Collections.Generic;
4using HeuristicLab.Persistence.Core;
5using HeuristicLab.Persistence.Interfaces;
6using System.Reflection;
7
8namespace HeuristicLab.Persistence.Default.Decomposers {
9 
10  public class KeyValuePairDecomposer : IDecomposer {   
11
12    public bool CanDecompose(Type type) {
13      return type.IsGenericType &&
14             type.GetGenericTypeDefinition() ==
15             typeof (KeyValuePair<int, int>).GetGenericTypeDefinition();
16    }
17
18    public IEnumerable<Tag> DeCompose(object o) {     
19      Type t = o.GetType();
20      yield return new Tag("key", t.GetProperty("Key").GetValue(o, null));
21      yield return new Tag("value", t.GetProperty("Value").GetValue(o, null));
22    }
23
24    public object CreateInstance(Type type) {
25      return Activator.CreateInstance(type, true);
26    }
27
28    public object Populate(object instance, IEnumerable<Tag> o, Type t) {
29      IEnumerator<Tag> iter = o.GetEnumerator();
30      iter.MoveNext();
31      FieldInfo keyFieldInfo =
32        t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
33        .Single(fi => fi.Name == "key");
34      FieldInfo valueFieldInfo =
35        t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
36        .Single(fi => fi.Name == "value");
37      iter.Current.SafeSet(value => keyFieldInfo.SetValue(instance, value));     
38      iter.MoveNext();
39      iter.Current.SafeSet(value => valueFieldInfo.SetValue(instance, value));
40      return instance;
41    }   
42  }
43
44}
Note: See TracBrowser for help on using the repository browser.