Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/Persistence/EnumerableFormatters.cs @ 1357

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

Pluginification and major refactoring. (#506)

File size: 2.2 KB
Line 
1using System.Collections;
2using System.Collections.Generic;
3using System.Text;
4using HeuristicLab.Persistence.Interfaces;
5using System;
6
7namespace HeuristicLab.Persistence {
8 
9
10  public abstract class NumberEnumeration2XmlFormatter : IFormatter {
11
12    public abstract Type Type { get; }
13    public IFormat Format { get { return XmlFormat.Instance; } }
14    protected virtual string Separator { get { return ";"; } }
15    protected abstract void Add(IEnumerable enumeration, object o);
16    protected abstract object Instantiate();
17    protected abstract string formatValue(object o);
18    protected abstract object parseValue(string o);
19
20    public object Serialize(object o) {
21      StringBuilder sb = new StringBuilder();
22      foreach (var value in (IEnumerable)o) {
23        sb.Append(formatValue(value));
24        sb.Append(Separator);
25      }
26      return sb.ToString();
27    }
28
29    public object DeSerialize(object o) {
30      IEnumerable enumeration = (IEnumerable)Instantiate();
31      string[] values = ((string)o).Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
32      foreach (var value in values) {
33        Add(enumeration, parseValue(value));
34      }
35      return enumeration;
36    }
37  }
38
39
40  public class IntList2XmlFormatter : NumberEnumeration2XmlFormatter {
41    public override Type Type { get { return typeof(List<int>); } }
42    protected override void Add(IEnumerable enumeration, object o) { ((List<int>)enumeration).Add((int)o); }
43    protected override object Instantiate() { return new List<int>(); }
44    protected override string formatValue(object o) { return o.ToString(); }
45    protected override object parseValue(string o) { return int.Parse(o); }
46  }
47
48
49  public class DoubleList2XmlFormatter : NumberEnumeration2XmlFormatter {
50    public override Type Type { get { return typeof(List<double>); } }
51    protected override void Add(IEnumerable enumeration, object o) { ((List<double>)enumeration).Add((int)o); }
52    protected override object Instantiate() { return new List<double>(); }
53    protected override string formatValue(object o) { return ((double)o).ToString("r"); }
54    protected override object parseValue(string o) { return double.Parse(o); }
55  }
56}
Note: See TracBrowser for help on using the repository browser.