Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/Number2StringConverter.cs @ 1625

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

Added PersistenceException used consistently for all error conditions in the persistence framework (#548)

File size: 2.1 KB
Line 
1using System;
2using HeuristicLab.Persistence.Interfaces;
3using HeuristicLab.Persistence.Core;
4using System.Collections.Generic;
5using System.Reflection;
6using System.Globalization;
7using System.Text;
8
9namespace HeuristicLab.Persistence.Default.Decomposers {
10
11  public class Number2StringConverter {
12
13    private static readonly List<Type> numberTypes =
14      new List<Type> {
15        typeof(bool),
16        typeof(byte),
17        typeof(sbyte),
18        typeof(short),
19        typeof(ushort),
20        typeof(int),
21        typeof(uint),
22        typeof(long),
23        typeof(ulong),
24        typeof(float),
25        typeof(double),
26        typeof(decimal),
27      };
28
29    private static readonly Dictionary<Type, MethodInfo> numberParsers;
30
31    static Number2StringConverter() {
32      numberParsers = new Dictionary<Type, MethodInfo>();
33      foreach (var type in numberTypes) {
34        numberParsers[type] = type
35          .GetMethod("Parse", BindingFlags.Static | BindingFlags.Public,
36                     null, new[] { typeof(string) }, null);
37      }
38    }
39
40    public bool CanDecompose(Type type) {
41      return numberParsers.ContainsKey(type);
42    }
43
44    public string Format(object obj) {
45      if (obj.GetType() == typeof(float))
46        return ((float)obj).ToString("r", CultureInfo.InvariantCulture);
47      if (obj.GetType() == typeof(double))
48        return ((double)obj).ToString("r", CultureInfo.InvariantCulture);
49      if (obj.GetType() == typeof(decimal))
50        return ((decimal)obj).ToString("r", CultureInfo.InvariantCulture);
51      return obj.ToString();
52    }
53
54    public object Parse(string stringValue, Type type) {
55      try {       
56        return numberParsers[type]
57          .Invoke(null,
58              BindingFlags.Static | BindingFlags.PutRefDispProperty,
59                    null, new[] { stringValue }, CultureInfo.InvariantCulture);
60      } catch (FormatException e) {
61        throw new PersistenceException("Invalid element data during number parsing.", e);
62      } catch (OverflowException e) {
63        throw new PersistenceException("Overflow during number parsing.", e);
64      }
65    }
66
67  }
68
69}
Note: See TracBrowser for help on using the repository browser.