Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/KeyValuePairDecomposer.cs @ 1542

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

Numerous small changes, coding conventions, renames, mini refactoring (#548)

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 int Priority {
13      get { return 100; }
14    }
15
16
17    public bool CanDecompose(Type type) {
18      return type.IsGenericType &&
19             type.GetGenericTypeDefinition() ==
20             typeof (KeyValuePair<int, int>).GetGenericTypeDefinition();
21    }
22
23    public IEnumerable<Tag> Decompose(object o) {     
24      Type t = o.GetType();
25      yield return new Tag("key", t.GetProperty("Key").GetValue(o, null));
26      yield return new Tag("value", t.GetProperty("Value").GetValue(o, null));
27    }
28
29    public object CreateInstance(Type type) {
30      return Activator.CreateInstance(type, true);
31    }
32
33    public object Populate(object instance, IEnumerable<Tag> o, Type t) {
34      IEnumerator<Tag> iter = o.GetEnumerator();
35      iter.MoveNext();
36      FieldInfo keyFieldInfo =
37        t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
38        .Single(fi => fi.Name == "key");
39      FieldInfo valueFieldInfo =
40        t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
41        .Single(fi => fi.Name == "value");
42      iter.Current.SafeSet(value => keyFieldInfo.SetValue(instance, value));     
43      iter.MoveNext();
44      iter.Current.SafeSet(value => valueFieldInfo.SetValue(instance, value));
45      return instance;
46    }   
47  }
48
49}
Note: See TracBrowser for help on using the repository browser.