-
Notifications
You must be signed in to change notification settings - Fork 35
/
ConvertT.cs
114 lines (96 loc) · 2.62 KB
/
ConvertT.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#if NET40_OR_GREATER || TARGETS_NETSTANDARD || TARGETS_NETCOREAPP // PUBLIC_API_CHANGES. TODO: update after fixes in Theraot.Core
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using JetBrains.Annotations;
namespace CodeJam.Mapping
{
using Expressions;
/// <summary>
/// Provides data conversion functionality.
/// </summary>
/// <typeparam name="TFrom">Type to convert from.</typeparam>
/// <typeparam name="TTo">Type to convert to.</typeparam>
[PublicAPI]
public static class Convert<TFrom, TTo>
{
static Convert()
{
Init();
}
[MemberNotNull(nameof(_expression))]
[MemberNotNull(nameof(_lambda))]
private static void Init()
{
var expr = ConvertBuilder.GetConverter(null, typeof(TFrom), typeof(TTo));
_expression = (Expression<Func<TFrom, TTo>>)expr.Item1;
var rexpr = (Expression<Func<TFrom, TTo>>)expr.Item1.Transform(e => e is DefaultValueExpression ? e.Reduce() : e);
_lambda = rexpr.Compile();
}
private static Expression<Func<TFrom, TTo>>? _expression;
/// <summary>
/// Represents an expression that converts a value of <i>TFrom</i> type to <i>TTo</i> type.
/// </summary>
[AllowNull]
public static Expression<Func<TFrom, TTo>> Expression
{
get => _expression!;
set
{
var setDefault = _expression != null;
if (value == null)
{
Init();
}
else
{
_expression = value;
_lambda = _expression.Compile();
}
if (setDefault)
ConvertInfo.Default.Set(
typeof(TFrom),
typeof(TTo),
new ConvertInfo.LambdaInfo(_expression, null, _lambda, false));
}
}
private static Func<TFrom, TTo> _lambda;
/// <summary>
/// Represents a function that converts a value of <i>TFrom</i> type to <i>TTo</i> type.
/// </summary>
[AllowNull]
public static Func<TFrom, TTo> Lambda
{
get => _lambda;
set
{
var setDefault = _expression != null;
if (value == null)
{
Init();
}
else
{
var p = System.Linq.Expressions.Expression.Parameter(typeof(TFrom), "p");
_lambda = value;
_expression =
System.Linq.Expressions.Expression.Lambda<Func<TFrom, TTo>>(
System.Linq.Expressions.Expression.Invoke(
System.Linq.Expressions.Expression.Constant(value),
p),
p);
}
if (setDefault)
ConvertInfo.Default.Set(
typeof(TFrom),
typeof(TTo),
new ConvertInfo.LambdaInfo(_expression, null, _lambda, false));
}
}
/// <summary>
/// Returns a function that converts a value of <i>TFrom</i> type to <i>TTo</i> type.
/// </summary>
public static Func<TFrom, TTo> From => _lambda;
}
}
#endif