1 | using System;
|
---|
2 | using HeuristicLab.Persistence.Interfaces;
|
---|
3 | using HeuristicLab.Persistence.Core;
|
---|
4 | using System.Collections.Generic;
|
---|
5 | using System.Reflection;
|
---|
6 | using System.Globalization;
|
---|
7 | using System.Text;
|
---|
8 |
|
---|
9 | namespace 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 | } |
---|