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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
|
// Copyright 2009-2022 Josh Close
// This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0.
// See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0.
// https://github.com/JoshClose/CsvHelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace CsvHelper
{
/// <summary>
/// Efficiently creates instances of object types.
/// </summary>
public class ObjectCreator
{
private readonly Dictionary<int, Func<object[], object>> cache = new Dictionary<int, Func<object[], object>>();
/// <summary>
/// Creates an instance of type T using the given arguments.
/// </summary>
/// <typeparam name="T">The type to create an instance of.</typeparam>
/// <param name="args">The constrcutor arguments.</param>
public T CreateInstance<T>(params object[] args)
{
return (T)CreateInstance(typeof(T), args);
}
/// <summary>
/// Creates an instance of the given type using the given arguments.
/// </summary>
/// <param name="type">The type to create an instance of.</param>
/// <param name="args">The constructor arguments.</param>
public object CreateInstance(Type type, params object[] args)
{
var func = GetFunc(type, args);
return func(args);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Func<object[], object> GetFunc(Type type, object[] args)
{
var argTypes = GetArgTypes(args);
var key = GetConstructorCacheKey(type, argTypes);
if (!cache.TryGetValue(key, out var func))
{
cache[key] = func = CreateInstanceFunc(type, argTypes);
}
return func;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Type[] GetArgTypes(object[] args)
{
var argTypes = new Type[args.Length];
for (var i = 0; i < args.Length; i++)
{
argTypes[i] = args[i]?.GetType() ?? typeof(object);
}
return argTypes;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int GetConstructorCacheKey(Type type, Type[] args)
{
#if !NET45
var hashCode = new HashCode();
hashCode.Add(type.GetHashCode());
for (var i = 0; i < args.Length; i++)
{
hashCode.Add(args[i].GetHashCode());
}
return hashCode.ToHashCode();
#else
unchecked
{
var hash = 17;
hash = hash * 31 + type.GetHashCode();
for (var i = 0; i < args.Length; i++)
{
hash = hash * 31 + (args[i].GetHashCode());
}
return hash;
}
#endif
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Func<object[], object> CreateInstanceFunc(Type type, Type[] argTypes)
{
var parameterExpression = Expression.Parameter(typeof(object[]), "args");
Expression body;
if (type.IsValueType)
{
if (argTypes.Length > 0)
{
throw GetConstructorNotFoundException(type, argTypes);
}
body = Expression.Convert(Expression.Default(type), typeof(object));
}
else
{
var constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var constructor = GetConstructor(constructors, type, argTypes);
var parameters = constructor.GetParameters();
var parameterTypes = new Type[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
{
parameterTypes[i] = parameters[i].ParameterType;
}
var arguments = new List<Expression>();
for (var i = 0; i < parameterTypes.Length; i++)
{
var parameterType = parameterTypes[i];
var arrayIndexExpression = Expression.ArrayIndex(parameterExpression, Expression.Constant(i));
var convertExpression = Expression.Convert(arrayIndexExpression, parameterType);
arguments.Add(convertExpression);
}
body = Expression.New(constructor, arguments);
}
var lambda = Expression.Lambda<Func<object[], object>>(body, new[] { parameterExpression });
var func = lambda.Compile();
return func;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static ConstructorInfo GetConstructor(ConstructorInfo[] constructors, Type type, Type[] argTypes)
{
var matchType = MatchType.Exact;
var fuzzyMatches = new List<ConstructorInfo>();
for (var i = 0; i < constructors.Length; i++)
{
var constructor = constructors[i];
var parameters = constructors[i].GetParameters();
if (parameters.Length != argTypes.Length)
{
continue;
}
for (var j = 0; j < parameters.Length && j < argTypes.Length; j++)
{
var parameterType = parameters[j].ParameterType;
var argType = argTypes[j];
if (argType == parameterType)
{
matchType = MatchType.Exact;
continue;
}
if (!parameterType.IsValueType && (parameterType.IsAssignableFrom(argType) || argType == typeof(object)))
{
matchType = MatchType.Fuzzy;
continue;
}
matchType = MatchType.None;
break;
}
if (matchType == MatchType.Exact)
{
// Only possible to have one exact match.
return constructor;
}
if (matchType == MatchType.Fuzzy)
{
fuzzyMatches.Add(constructor);
}
}
if (fuzzyMatches.Count == 1)
{
return fuzzyMatches[0];
}
if (fuzzyMatches.Count > 1)
{
throw new AmbiguousMatchException();
}
throw GetConstructorNotFoundException(type, argTypes);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static MissingMethodException GetConstructorNotFoundException(Type type, Type[] argTypes)
{
var signature = $"{type.FullName}({string.Join(", ", argTypes.Select(a => a.FullName))})";
throw new MissingMethodException($"Constructor '{signature}' was not found.");
}
private enum MatchType
{
None = 0,
Exact = 1,
Fuzzy = 2
}
}
}
|