-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathGetValueComparator.IlGetter.cs
More file actions
64 lines (51 loc) · 2.11 KB
/
GetValueComparator.IlGetter.cs
File metadata and controls
64 lines (51 loc) · 2.11 KB
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
using System.Reflection;
using System.Reflection.Emit;
namespace PhenX.EntityFrameworkCore.BulkInsert.Benchmark;
public partial class GetValueComparator
{
public static Func<object, object?> CreateUntypedGetter(PropertyInfo propertyInfo, Type sourceType, Type valueType)
{
var method =
typeof(GetValueComparator).GetMethod(nameof(CreateInternalUntypedGetter), BindingFlags.NonPublic | BindingFlags.Static)!
.MakeGenericMethod(sourceType, valueType);
return (Func<object, object?>)method.Invoke(null, [propertyInfo])!;
}
private static Func<object, object?> CreateInternalUntypedGetter<TSource, TValue>(PropertyInfo propertyInfo)
{
var getter = CreateGetter<TSource, TValue>(propertyInfo);
return source => getter((TSource)source!);
}
public static Func<TSource, TValue> CreateGetter<TSource, TValue>(PropertyInfo propertyInfo)
{
if (!propertyInfo.CanRead)
{
return x => throw new NotSupportedException();
}
var bakingField =
propertyInfo.DeclaringType!.GetField($"<{propertyInfo.Name}>k__BackingField",
BindingFlags.NonPublic |
BindingFlags.Instance);
var propertyGetMethod = propertyInfo.GetGetMethod()!;
var getMethod = new DynamicMethod(propertyGetMethod.Name, typeof(TValue), [typeof(TSource)], true);
var getGenerator = getMethod.GetILGenerator();
// Load this to stack.
getGenerator.Emit(OpCodes.Ldarg_0);
if (bakingField != null && !propertyGetMethod.IsVirtual)
{
// Get field directly.
getGenerator.Emit(OpCodes.Ldfld, bakingField);
}
else if (propertyGetMethod.IsVirtual)
{
// Call the virtual property.
getGenerator.Emit(OpCodes.Callvirt, propertyGetMethod);
}
else
{
// Call the non virtual property.
getGenerator.Emit(OpCodes.Call, propertyGetMethod);
}
getGenerator.Emit(OpCodes.Ret);
return getMethod.CreateDelegate<Func<TSource, TValue>>();
}
}