Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/NumberEnumeration2XmlFormatterBase.cs @ 1659

Last change on this file since 1659 was 1659, checked in by epitzer, 16 years ago

Add missing attributes and create type hierarchy for formatters. (#548)

File size: 1.5 KB
Line 
1using System.Collections;
2using System.Text;
3using HeuristicLab.Persistence.Interfaces;
4using System;
5using HeuristicLab.Persistence.Core;
6
7namespace HeuristicLab.Persistence.Default.Xml.Compact {
8
9  public abstract class NumberEnumeration2XmlFormatterBase<T> : CompactXmlFormatterBase<T> where T : IEnumerable {
10
11    protected virtual string Separator { get { return ";"; } }
12    protected abstract void Add(IEnumerable enumeration, object o);
13    protected abstract IEnumerable Instantiate();
14    protected abstract string FormatValue(object o);
15    protected abstract object ParseValue(string o);
16
17    public override XmlString Format(T t) {
18      StringBuilder sb = new StringBuilder();
19      foreach (var value in (IEnumerable)t) {
20        sb.Append(FormatValue(value));
21        sb.Append(Separator);
22      }
23      return new XmlString(sb.ToString());
24    }
25
26    public override T Parse(XmlString x) {
27      try {
28        IEnumerable enumeration = Instantiate();
29        string[] values = x.Data.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
30        foreach (var value in values) {
31          Add(enumeration, ParseValue(value));
32        }
33        return (T)enumeration;
34      } catch (InvalidCastException e) {
35        throw new PersistenceException("Invalid element data during reconstruction of number enumerable.", e);
36      } catch (OverflowException e) {
37        throw new PersistenceException("Overflow during element parsing while trying to reconstruct number enumerable.", e);
38      }       
39    }
40  }
41
42}
Note: See TracBrowser for help on using the repository browser.