/
Conversions.cs
executable file
·75 lines (63 loc) · 2.41 KB
/
Conversions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using System.Collections.Generic;
using FubuCore.Util;
namespace StoryTeller.Conversion
{
public class Conversions
{
private readonly IList<IRuntimeConverter> _runtimeConvertors = new List<IRuntimeConverter>();
private readonly IList<IConversionProvider> _providers = new List<IConversionProvider>();
private readonly Cache<Type, Func<string, object>> _convertors;
public Conversions()
{
_convertors =
new Cache<Type, Func<string, object>>(
type =>
{
return
_providers.UnionWith(new EnumerationConversion(), new NullableConvertor(this), new ArrayConversion(this), new StringConverterProvider())
.FirstValue(x => x.ConverterFor(type));
});
RegisterConversion(bool.Parse);
RegisterConversion(byte.Parse);
RegisterConversion(sbyte.Parse);
RegisterConversion(char.Parse);
RegisterConversion(decimal.Parse);
RegisterConversion(double.Parse);
RegisterConversion(Single.Parse);
RegisterConversion(Int16.Parse);
RegisterConversion(Int32.Parse);
RegisterConversion(Int64.Parse);
RegisterConversion(UInt16.Parse);
RegisterConversion(UInt32.Parse);
RegisterConversion(UInt64.Parse);
RegisterConversion(DateTimeConverter.GetDateTime);
RegisterConversion(x =>
{
if (x == "EMPTY") return string.Empty;
return x;
});
}
public IEnumerable<IRuntimeConverter> RuntimeConvertors => _runtimeConvertors;
public void RegisterRuntimeConversion<T>() where T : IRuntimeConverter, new()
{
_runtimeConvertors.Add(new T());
}
public void RegisterConversionProvider<T>() where T : IConversionProvider, new()
{
_providers.Add(new T());
}
public void RegisterConversion<T>(Func<string, T> convertor)
{
_convertors[typeof (T)] = x => convertor(x);
}
public Func<string, object> FindConverter(Type type)
{
return _convertors[type];
}
public object Convert(Type type, string raw)
{
return _convertors[type](raw);
}
}
}